<?php
namespace app\api\controller;
use think\Db;

class Shop extends Base
{

    public function _initialize()
{
    extract(input());
    $sta = $this->checkAll1 ($shop_id,$time,$value,$reqKey);
    if(!$sta){
        return json(['status'=>301,'msg'=>'Token失效！请重新登录！']);
    }
    parent::_initialize ();
}



    public function homePage(){
        extract(input());
        $shop = Db::name('shop')
            ->where(['shop_id'=>$shop_id])
            ->field(['shop_id','shop_browse','shop_all_balance','dx_status'])
            ->find();
        $today = Db::name('order')
            ->where(['o_shop_id'=>$shop_id,'o_type'=>['in','1,2']])
            ->whereTime('o_add_time', 'today')
            ->count();
        $shop['today_order'] = $today;
        $j_1 = Db::name('order')
            ->where(['o_shop_id'=>$shop_id,'o_type'=>1,'o_status'=>2])
            ->count();
        $jifen['j_1'] = $j_1;
        $j_2 = Db::name('order')
            ->where(['o_shop_id'=>$shop_id,'o_type'=>1,'o_status'=>3])
            ->count();
        $jifen['j_2'] = $j_2;
        $j_3 = Db::name('order')
            ->where(['o_shop_id'=>$shop_id,'o_type'=>1,'o_status'=>10])
            ->count();
        $jifen['j_3'] = $j_3;
        $j_4 = Db::name('order')
            ->where(['o_shop_id'=>$shop_id,'o_type'=>1,'o_status'=>6])
            ->count();
        $jifen['j_4'] = $j_4;
        $x_1 = Db::name('order')
            ->where(['o_shop_id'=>$shop_id,'o_type'=>2,'o_status'=>2])
            ->count();
        $sell['x_1'] = $x_1;
        $x_2 = Db::name('order')
            ->where(['o_shop_id'=>$shop_id,'o_type'=>2,'o_status'=>3])
            ->count();
        $sell['x_2'] = $x_2;
        $x_3 = Db::name('order')
            ->where(['o_shop_id'=>$shop_id,'o_type'=>2,'o_status'=>['in','4,5']])
            ->count();
        $sell['x_3'] = $x_3;
        $x_4 = Db::name('order')
            ->where(['o_shop_id'=>$shop_id,'o_type'=>2,'o_refund'=>1])
            ->count();
        $sell['x_4'] = $x_4;
        $x_5 = Db::name('order')
            ->where(['o_shop_id'=>$shop_id,'o_type'=>2,'o_status'=>10])
            ->count();
        $sell['x_5'] = $x_5;
        $shop['jifen'] = $jifen;
        $shop['sell'] = $sell;
        $tan = '';
        if($shop['dx_status'] == 0) $tan = '请前往资料页面完善中国电信翼支付认证后再使用支分宝商家版！';
        return json(['status'=>200,'msg'=>$shop,'tan'=>$tan]);
    }


    public function setShop(){
        extract(input());
        $param = [
            'shop_banner'=>$banner,
            'shop_link'=>$link,
            'shop_video_link'=>$video_link,
            'shop_cover'=>$cover,
            'shop_name'=>$name,
            'shop_img'=>$image,
            'shop_business_hours'=>$business_hours,
            'shop_introduce'=>$introduce,
            'shop_address'=>$address,
            'shop_contact'=>$contact,
            'shop_edit_time'=>date('Y-m-d H:i:s'),
            'shop_lon'=>$lon,
            'shop_lat'=>$lat
        ];
        $res = Db::name('shop')->where('shop_id',$shop_id)->update($param);
        if($res){
            return json(['status'=>200,'msg'=>'编辑成功']);
        }else{
            return json(['status'=>100,'msg'=>'编辑失败']);
        }
    }



    public function goodsControl(){
        extract(input());
        $where = [
            'p_shop_id'=>$shop_id
        ];
        switch($type){
            case 1:
                $where['p_status'] = 4;
                break;
            case 2:
                $where['p_status'] = 1;
                break;
            case 3:
                $where['p_status'] = ['in','3,5'];
                break;
        }
        $data = Db::name('product')
            ->where($where)
            ->field(['p_id','p_type','p_banner','p_shop_id','p_name','p_now_price','p_jifen_price','p_stock_num','p_sell_yet','p_model'])
            ->order('p_edit_time desc')
            ->page($page,10)
            ->select ();
        $count1 = Db::name('product')->where(['p_shop_id'=>$shop_id,'p_status'=>4])->count();
        $count2 = Db::name('product')->where(['p_shop_id'=>$shop_id,'p_status'=>1])->count();
        $count3 = Db::name('product')->where(['p_shop_id'=>$shop_id,'p_status'=>['in','3,5']])->count();
        if(!empty($data)){
            foreach($data as $key=>$vo){
                if($vo['p_model'] == 2){
                    $model = Db::name('product_model')
                        ->where(['m_product_id'=>$vo['p_id']])
                        ->field(['max(m_price)'=>'max_price','min(m_price)'=>'min_price','max(m_integral)'=>'max_integral','min(m_integral)'=>'min_integral','sum(m_num)'=>'m_num'])
                        ->find ();
                    $data[$key]['p_now_price'] = $model['min_price'].'-'.$model['max_price'];
                    $data[$key]['p_jifen_price'] = $model['min_integral'].'-'.$model['max_integral'];
                    $data[$key]['p_stock_num'] = $model['m_num'];
                }
            }
        }
        return json(['status'=>200,'msg'=>['data'=>$data,'count1'=>$count1,'count2'=>$count2,'count3'=>$count3]]);
    }

    public function supplement(){
        extract (input());
        if($type == 1){
            $data = Db::name('product')
                ->where('p_id',$p_id)
                ->field(['p_id'=>'m_id','p_stock_num'=>'m_num','p_model'])
                ->find();
            $arr['model'] = 1;
            if($data['p_model'] == 2){
                $data = Db::name('product_model')
                    ->where('m_product_id',$p_id)
                    ->field(['m_id','m_name','m_num'])
                    ->select();
                $arr['model'] = 2;
            }
            $arr['data'] = $data;
            return json(['status'=>200,'msg'=>$arr]);
        }else{
            if($model == 1){
                $res = Db::name('product')->where('p_id',$p_id)->setField ('p_stock_num',$num);
            }else{
                $res = Db::name('product_model')->where('m_id',$m_id)->setField ('m_num',$num);
            }
            if($res){
                return json(['status'=>200,'msg'=>'补充库存成功']);
            }else{
                return json(['status'=>100,'msg'=>'补充库存失败']);
            }
        }
    }



    public function changeStatus(){
        extract (input());
        if($type == 1){
            $val = 5;
            $msg = '下架';
        }else{
            $val = 1;
            $msg = '上架';
        }
//        if($type == 2){
//            $shop = Db::name('shop')->where('shop_id',$shop_id)->find();
//            $goods = Db::name('product')->where('p_id',$p_id)->find();
//            if($goods['p_give'] > 0 && $goods['p_give'] > $shop['shop_integral']){
//                return json(['status'=>100,'msg'=>'积分押金不足，请尽快充值押金']);
//            }
//        }
        $res = Db::name('product')->where('p_id',$p_id)->setField ('p_status',$val);
        if($res){
            return json(['status'=>200,'msg'=>$msg.'成功']);
        }else{
            return json(['status'=>100,'msg'=>$msg.'失败']);
        }
    }


    public function delGoods(){
        extract (input());
        $res = Db::name('product')->where('p_id',$p_id)->update (['p_status'=>$type,'p_edit_time'=>date('Y-m-d H:i:s')]);
        if($res){
            return json(['status'=>200,'msg'=>'删除成功']);
        }else{
            return json(['status'=>100,'msg'=>'删除失败']);
        }
    }


    public function releaseNewProduct(){
        extract(input());
        $shop = Db::name('shop')->where('shop_id',$shop_id)->find();

//        if($shop['shop_pledge_money'] == 0){
//            return json(['status'=>100,'msg'=>'需交押金后才可以发布商品']);
//        }
        $rate = Db::name('jifen_conf')->where(['conf_id'=>1])->value('conf_rate');
        $time = date('Y-m-d H:i:s');
        $param = [
            'p_shop_id'=>$shop_id,
            'p_type'=>1,
            'p_banner'=>$banner,
            'p_video'=>$video,
            'p_name'=>$p_name,
            'p_cate'=>$cate_id,
            'p_old_price'=>$old_price,
            'p_model'=>$model,
            'p_content'=>$content,
            'p_deliver_cate'=>$deliver_cate,
            'p_postage'=>$postage,
            'p_equity'=>$equity,
            'p_status'=>1,
            'p_add_time'=>$time,
            'p_edit_time'=>$time,
            'p_give'=>$give
        ];
        $now_price_rate = DB::name('jifen_conf')->where(['conf_id'=>26])->value('conf_rate');
        if($model == 1){
            $param['p_now_price'] = $now_price;
            $param['p_stock_num'] = $stock_num;
            $give_jifen = $now_price * $now_price_rate/$rate;
            $give_jifen = ceil($give_jifen);
            if ($give_jifen > $give) {
//                $now_price_rate_num = $now_price_rate*100;
//                return json(['status'=>100,'msg'=>'请赠送现金'.$now_price_rate_num.'%以上的积分']);
                return json(['status'=>100,'msg'=>'当前价格需最低送出 '.$give_jifen.' 积分']);
            }
        }else{
            $now_price = explode(',',$now_price);
            $model_name = explode(',',$model_name);
            $stock_num = explode(',',$stock_num);
            $param['p_now_price'] = $now_price[0];
            $give_jifen = $now_price[0] * $now_price_rate/$rate;
            $give_jifen = ceil($give_jifen);
            if ($give_jifen > $give) {
//                $now_price_rate_num = $now_price_rate*100;
//                return json(['status'=>100,'msg'=>'请赠送现金'.$now_price_rate_num.'%以上的积分']);
                return json(['status'=>100,'msg'=>'当前价格需最低送出 '.$give_jifen.' 积分']);
            }
        }
        Db::startTrans ();
        try{
            $p_id = Db::name('product')->insertGetId ($param);
            if($model == 2){
                for($i=0;$i<count($now_price);$i++){
                    $data[] = ['m_name'=>$model_name[$i],'m_price'=>$now_price[$i],'m_num'=>$stock_num[$i],'m_product_id'=>$p_id,'m_add_time'=>$time,'m_edit_time'=>$time];
                }
                Db::name('product_model')->insertAll($data);
            }
            Db::commit ();
            return json(['status'=>200,'msg'=>'发布成功']);
        }catch (\Exception $e){
            Db::rollback ();
            return json(['status'=>100,'msg'=>'发布失败']);
        }
    }


    public function getGoodsInfo(){
        extract(input());
        $data = Db::name('product')
            ->where('p_id',$p_id)
            ->find();
        $data['model'] = [];
        if($data['p_model'] == 2){
            $data['model'] = Db::name('product_model')->where('m_product_id',$p_id)->select ();
        }
        if($type == 1 && $data['p_game'] == 2){
            return json(['status'=>100,'msg'=>'请勿重复推广']);
        }elseif($type == 2 && $data['p_extend'] == 2){
            return json(['status'=>100,'msg'=>'请勿重复推广']);
        }else{
            return json(['status'=>200,'msg'=>$data]);
        }
    }




    public function newJifenGoods(){
        extract(input());
        $data = Db::name('product')->where('p_id',$p_id)->find();
        $time = date("Y-m-d H:i:s");
        $param = [
            'p_shop_id'=>$shop_id,
            'p_type'=>$type,
            'p_banner'=>$banner,
            'p_video'=>$video,
            'p_name'=>$p_name,
            'p_cate'=>$data['p_cate'],
            'p_model'=>$model,
            'p_content'=>$data['p_content'],
            'p_deliver_cate'=>$deliver_cate,
            'p_postage'=>$postage,
            'p_equity'=>$equity,
            'p_status'=>1,
            'p_start_time'=>$start_time,
            'p_end_time'=>$end_time,
            'p_add_time'=>$time,
            'p_edit_time'=>$time,
            'p_buy_limit'=>$buy_limit
        ];
        if($model == 1){
            if($mixture == 2) {
                $param[ 'p_now_price' ] = $now_price;
            }
            $param['p_stock_num'] = $stock_num;
            $param['p_jifen_price'] = $jifen_price;
        }else{
            $now_price = explode (',',$now_price);
            $jifen_price = explode (',',$jifen_price);
            if($mixture == 2) {
                $param[ 'p_now_price' ] = $now_price[0];
            }
            $param['p_jifen_price'] = $jifen_price[0];
        }
        Db::startTrans ();
        try{
            $p_id = Db::name('product')->insertGetId ($param);
            if($model == 2){
                $model_name = explode (',',$model_name);
                $stock_num = explode (',',$stock_num);
                $datas = [];
                if($mixture == 1){
                    for($i=0;$i<count($jifen_price);$i++){
                        $datas[] = ['m_name'=>$model_name[$i],'m_integral'=>$jifen_price[$i],'m_num'=>$stock_num[$i],'m_product_id'=>$p_id,'m_add_time'=>$time,'m_edit_time'=>$time];
                    }
                }else{
                    for($i=0;$i<count($jifen_price);$i++){
                        $datas[] = ['m_name'=>$model_name[$i],'m_integral'=>$jifen_price[$i],'m_price'=>$now_price[$i],'m_num'=>$stock_num[$i],'m_product_id'=>$p_id,'m_add_time'=>$time,'m_edit_time'=>$time];
                    }
                }
                Db::name('product_model')->insertAll($datas);
                Db::name('product')->where('p_id',$p_id)->setField ('p_extend',2);
            }
            Db::commit ();
            return json(['status'=>200,'msg'=>'发布成功']);
        }catch (\Exception $e){
            Db::rollback ();
            return json(['status'=>100,'msg'=>'发布失败']);
        }
    }


    /**
     * 编辑积分商品
     * @return \think\response\Json
     */
    public function editJifenGoods(){
        extract(input());
        if($edit_type == 1){
            $data = Db::name('product')
                ->where('p_id',$p_id)
                ->find();
            if($data['p_model'] == 2){//有型号
                $model = Db::name('product_model')
                    ->where('m_product_id',$p_id)
                    ->select ();
                $data['model'] = $model;
            }
            return json(['status'=>200,'msg'=>$data]);
        }else{
            $time = date('Y-m-d H:i:s');
            $param = [
                'p_shop_id'=>$shop_id,
                'p_type'=>$type,//2：纯积分商品  3：现金加积分商品
                'p_banner'=>$banner,
                'p_video'=>$video,
                'p_name'=>$p_name,
                // 'p_cate'=>$cate_id,
                'p_model'=>$model,
                // 'p_content'=>$content,
                'p_deliver_cate'=>$deliver_cate,
                'p_postage'=>$postage,
                'p_equity'=>$equity,
                'p_status'=>1,
                'p_start_time'=>$start_time,
                'p_end_time'=>$end_time,
                'p_edit_time'=>$time,
                'p_buy_limit'=>$buy_limit
            ];
            if($model == 1){//1:无型号
                if($mixture == 2) {//混合价格
                    $param[ 'p_now_price' ] = $now_price;
                }
                $param['p_stock_num'] = $stock_num;
                $param['p_jifen_price'] = $jifen_price;
            }else{ //有型号
                $jifen_price = explode (',',$jifen_price);
                if($mixture == 2) {//混合价格
                    $now_price = explode (',',$now_price);
                    $param[ 'p_now_price' ] = $now_price[0];
                }
                $param['p_jifen_price'] = $jifen_price[0];
            }
            Db::startTrans ();
            try{
                Db::name('product')->where('p_id',$p_id)->update ($param);
                if($model == 2){//2：有型号
                    $model_id = explode (',',$model_id);
                    $model_name = explode (',',$model_name);
                    $stock_num = explode (',',$stock_num);
                    // $datas = [];
                    if($mixture == 1){//未混合价格
                        for($i=0;$i<count($jifen_price);$i++){
                            Db::name('product_model')->where('m_id',$model_id[$i])->update(['m_name'=>$model_name[$i],'m_integral'=>$jifen_price[$i],'m_num'=>$stock_num[$i],'m_product_id'=>$p_id,'m_edit_time'=>$time]);
                        }
                    }else{//混合价格
                        for($i=0;$i<count($jifen_price);$i++){
                            Db::name('product_model')->where('m_id',$model_id[$i])->update(['m_name'=>$model_name[$i],'m_integral'=>$jifen_price[$i],'m_price'=>$now_price[$i],'m_num'=>$stock_num[$i],'m_product_id'=>$p_id,'m_edit_time'=>$time]);
                        }
                    }
                }else{//1：无型号
                    Db::name('product_model')->where('m_product_id',$p_id)->delete ();//删除已有的所有型号
                }
                Db::commit ();
                return json(['status'=>200,'msg'=>'编辑成功']);
            }catch (\Exception $e){
                Db::rollback ();
                return json(['status'=>100,'msg'=>'编辑失败']);
            }
        }
    }



    public function editGoods(){
        extract(input());
        if($type == 1){
            $data = Db::name('product')
                ->where('p_id',$p_id)
                ->field(['p_id','p_shop_id','p_banner','p_video','p_name','p_cate','p_old_price','p_now_price','p_stock_num','p_sell_yet','p_model','p_content','p_deliver_cate','p_postage','p_equity','p_status','p_give'])
                ->find();
            if($data['p_model'] == 2){
                $model = Db::name('product_model')
                    ->where('m_product_id',$p_id)
                    ->field(['m_id','m_name','m_price','m_num'])
                    ->select ();
                $data['model'] = $model;
            }
            return json(['status'=>200,'msg'=>$data]);
        }else{
            $time = date('Y-m-d H:i:s');
            $param = [
                'p_shop_id'=>$shop_id,
                'p_type'=>1,
                'p_banner'=>$banner,
                'p_video'=>$video,
                'p_name'=>$p_name,
                'p_cate'=>$cate_id,
                'p_old_price'=>$old_price,
                'p_model'=>$model,
                'p_content'=>$content,
                'p_deliver_cate'=>$deliver_cate,
                'p_postage'=>$postage,
                'p_equity'=>$equity,
                'p_status'=>1,
                'p_edit_time'=>$time,
                'give'=>$give
            ];
            if($model == 1){
                $param['p_now_price'] = $now_price;
                $param['p_stock_num'] = $stock_num;
            }
            Db::startTrans ();
            try{
                Db::name('product')->where('p_id',$p_id)->update ($param);
                if($model == 2){
                    for($i=0;$i<count($now_price);$i++){
                        Db::name('product_model')->where('m_id',$model_id[$i])->update(['m_name'=>$model_name[$i],'m_price'=>$now_price[$i],'m_num'=>$stock_num[$i],'m_edit_time'=>$time]);
                    }
                }else{
                    Db::name('product_model')->where('m_product_id',$p_id)->delete ();
                }
                Db::commit ();
                return json(['status'=>200,'msg'=>'编辑成功']);
            }catch (\Exception $e){
                Db::rollback ();
                return json(['status'=>100,'msg'=>'编辑失败']);
            }
        }
    }


    public function getCatList(){
        $data = Db::name('product_cate')
            ->field(['cate_id'=>'id','cate_name','cate_pid'=>'pid'])
            ->order ('cate_sort ASC')
            ->select ();
        $data = generateTree($data);
       return json(['status'=>200,'msg'=>$data]);
    }


    public function myWallet(){
        extract(input());
        $data = Db::name('shop')
            ->where('shop_id',$shop_id)
            ->field('shop_id,shop_name,shop_balance,shop_balance_yet,shop_pledge_money,shop_card,shop_phone,shop_integral,shop_user_name,shop_wx_account,shop_ali_account,shop_wx_openid')
            ->find();
        return json(['status'=>200,'msg'=>$data]);
    }


    public function getBalanceInfo(){
//        $page=1;$shop_id=1;
//        extract(input());
//        $rate = Db::name('jifen_conf')->where('conf_id',2)->value('conf_rate');
//        $data = Db::name('order o')
//            ->join('order_info i','i.oi_order_id = o.o_id','left')
//            ->where(['o_shop_id'=>$shop_id,'o_type'=>['in','1,2,3,6,10'],'o_status'=>['in','4,5,6,8'],'o_pay_status'=>2,'o_esp'=>1])
//            ->field(['o_id,o_type,o_money,o_jifen,o_add_time,oi_goods_name,oi_num,oi_total_price,oi_total_jifen'])
//            ->order('o_add_time desc')
//            ->page($page,10)
//            ->select ();
//        if(!empty($data)){
//            foreach($data as $key=>$vo){
//                if($vo['o_jifen'] > 0 && in_array($vo['o_type'],[1,2])){
//                    $data[$key]['oi_total_price'] = round($vo['o_jifen'] * $rate + $vo['o_money'],2);
//                }else{
//                    $data[$key]['oi_total_price'] = $vo['o_money'];
//                }
//                $data[$key]['o_add_time'] = get_time(strtotime ($vo['o_add_time']));
//            }
//        }
//        return json(['status'=>200,'msg'=>$data]);
        extract(input());
        $page = ($page - 1) * 10;
        $data = DB::query("SELECT
            *
        FROM
            (
                (
                    SELECT
                        o_id,
                        1 AS record_jilu,
                        0 AS record_give_jifen,
                        o_m_yajin,
                        o_type,
                        o_money,
                        o_jifen,
                        o_m_type,
                        o_m_money,
                        o_add_time,
                        oi_goods_name,
                        oi_num,
                        oi_total_price,
                        oi_total_jifen,
                        1 AS type,
                        1 AS record_fws
                    FROM
                        up_order o
                    LEFT JOIN up_order_info i ON i.oi_order_id = o.o_id
                    WHERE
                        o.o_shop_id ={$shop_id}
                    AND o.o_type IN (1, 2, 3, 6, 10)
                    AND o.o_status IN (4, 5, 6, 8)
                    AND o.o_pay_status = 2
                    AND o.o_esp = 1
                )
                UNION ALL
                (
                    SELECT
                        record_id AS o_id,
                        record_jilu,
                        record_give_jifen,
                        0 AS o_m_yajin,
                        1 AS o_type,
                        record_money AS o_money,
                        record_jifen AS o_jifen,
                        record_m_type AS o_m_type,
                        record_m_type AS o_m_money,
                        record_pay_time AS o_add_time,
                        if (record_type = 3,'刷脸支付（翼支付次日自动结算）', '扫码') AS oi_goods_name,
                        1 AS oi_num,
                        IF(record_jifen>0,CONCAT(record_money,'（',record_jifen,'积分）'),record_money) AS oi_total_price,
                        record_jifen AS oi_total_jifen,
                        2 AS type,
                        record_fws
                    FROM
                        up_record r
                    WHERE
                        r.record_shop_id ={$shop_id}
                    AND r.record_status = 2
                )
                UNION ALL
                (
                    SELECT
                        o_id,
                        1 AS record_jilu,
                        0 AS record_give_jifen,
                        o_m_yajin,
                        o_type,
                        o_money,
                        o_jifen,
                        o_m_type,
                        o_m_money,
                        o_add_time,
                        '' oi_goods_name,
                        1 oi_num,
                        o_money oi_total_price,
                        o_jifen oi_total_jifen,
                        3 AS type,
                        1 AS record_fws
                    FROM
                        up_order o
                    WHERE
                        o.o_shop_id ={$shop_id}
                    AND o.o_type = 4
                    AND o.o_status = 5
                    AND o.o_pay_status = 2
                    AND o.o_pay_type = 3
                    AND o.o_esp = 1
                )
            ) AS L
        ORDER BY
            L.o_add_time DESC
        LIMIT {$page},
         10");
        $rate = Db::name('jifen_conf')->where('conf_id',2)->value('conf_rate');
        $rate2 = Db::name('jifen_conf')->where('conf_id',1)->value('conf_rate');
        if(!empty($data)){
            $i = 1;
            foreach($data as $key=>$vo){
                if($vo['type'] == 1){
                    if($vo['o_jifen'] > 0 && in_array($vo['o_type'],[1,2])){
                        $data[$key]['oi_total_price'] = round($vo['o_jifen'] * $rate + $vo['o_money'],2);
                    }else{
                        $data[$key]['oi_total_price'] = $vo['o_money'];
                    }
                }
                if($vo['o_m_type'] != 1){
                    $insert = $vo;
                    $insert['o_type'] = 100;
                    $insert['o_money'] = $vo['o_m_money'];
                    $insert['o_m_type'] = 100;
                    $insert['o_add_time'] = $vo['o_add_time'];
                    $insert['oi_goods_name'] = $vo['o_m_type'] == 2 ? '分佣推广佣金' : '团团赚推广佣金';
                    array_splice($data, $key+$i, 0, array($insert));
                    $i++;
                }
                if($vo['record_jilu'] > 1 && $vo['record_give_jifen'] > 0 && $vo['oi_goods_name'] == '扫码'){
                    $insert = $vo;
                    $insert['o_type'] = 100;
                    $insert['o_money'] = $vo['record_give_jifen'] * $rate2;
                    $insert['o_m_type'] = 100;
                    $insert['o_add_time'] = $vo['o_add_time'];
                    $insert['oi_goods_name'] = '积分款扣除';
                    array_splice($data, $key+$i, 0, array($insert));
                    $i++;
                }
                if($vo['o_m_yajin'] > 0){
                    $insert = $vo;
                    $insert['o_type'] = 100;
                    $insert['o_money'] = $vo['o_m_yajin'];
                    $insert['o_m_type'] = 100;
                    $insert['o_add_time'] = $vo['o_add_time'];
                    $insert['oi_goods_name'] = '押金抵扣';
                    array_splice($data, $key+$i, 0, array($insert));
                    $i++;
                }
            }
        }
        if(!empty($data)){
            foreach($data as $key=>$vo){
                $data[$key]['o_add_time'] = get_time(strtotime ($vo['o_add_time']));
                if($vo['record_fws'] == 2 && $vo['oi_goods_name'] == '扫码') $data[$key]['oi_goods_name'] = '扫码（翼支付次日自动结算）';
            }
        }
        return json(['status'=>200,'msg'=>$data]);
    }



    public function balanceUp(){
        extract(input());
        $order = $this->getOrderNumber ();
        $param = [
            'o_type'=>6,
            'o_order_num'=>$order,
            'o_money'=>$money,
            'o_status'=>5,
            'o_pay_type'=>$type,
            'o_pay_status'=>1,
            'o_shop_id'=>$shop_id,
            'o_add_time'=>date('Y-m-d H:i:s')
        ];
        Db::name('order')->insert($param);
        if($type == 1){
            $ali = new Ali();
            $res = $ali->getParam($order,$money,'balanceUp','账户余额充值');
        }else{
            $wx = new Weixinshop();
            $obj = [
                'attach'=>"balanceUp",
                'body'=>"账户余额充值",
                'total_fee'=>$money * 100,
                'out_trade_no'=>$order,
                'product_id'=>"",
                'trade_type'=>"APP"
            ];
            $res = $wx->WeChatPayReady($obj);
        }
        return json(['status'=>200,'msg'=>$res]);
    }


    public function withdrawDepositList(){
        extract(input());
        if($type == 1){
            $map = [
                'o_shop_id'=>$shop_id,
                'o_type'=>3,
                'o_tixian_status'=>2
            ];
        }else{
            $map = [
                'o_shop_id'=>$shop_id,
                'o_type'=>3,
                'o_tixian_status'=>['in','1,4']
            ];
        }
        $data = Db::name('order')
            ->where($map)
            ->order ('o_add_time desc')
            ->page($page,10)
            ->select();
        if(!empty($data)){
            foreach($data as $key=>$vo){
                $data[$key]['o_add_time'] = get_time(strtotime ($vo['o_add_time']));
            }
        }
        return json(['status'=>200,'msg'=>$data]);
    }



    public function withdrawData(){
        extract (input());
        if($code == ''){
            return json(['status'=>100,'msg'=>'请填写验证码']);
        }
        $phone_code = Db::name('phonecode')->where(['phone'=>$phone,'status'=>0,'type'=>2])->find();
        if(empty($phone_code)){
            return json(['status'=>100,'msg'=>'请先发送验证码']);
        }
        $diff = time() - $phone_code['time'];
        if($diff >= 30*60){
            return json(['status'=>100,'msg'=>'验证码已失效']);
        }
        if($code != $phone_code['code']){
            return json(['status'=>100,'msg'=>'验证码输入错误']);
        }

        $res = Db::name('shop')
            ->where('shop_id',$shop_id)
            ->update(['shop_phone'=>$phone,'shop_card'=>$card,'shop_user_name'=>$name,'shop_wx_account'=>$wx,'shop_ali_account'=>$ali,'shop_wx_openid'=>$openid]);
        if($res){
            Db::name('phonecode')->where(['id'=>$phone_code['id']])->setField ('status',1);
            return json(['status'=>200,'msg'=>'提交成功']);
        }else{
            return json(['status'=>100,'msg'=>'提交失败']);
        }
    }



    public function withdrawDeposit(){
        extract (input());
        $shop_copy = Db::name('shop_copy')
            ->where('sc_dx_mch_status',2)
            ->where('sc_shop_id',$shop_id)
            ->field('sc_dx_mch_id')
            ->find();
        if(!$shop_copy || !$shop_copy['sc_dx_mch_id']) return json(['status'=>100,'msg'=>'请在资料页完成中国电信商家认证后再使用提现功能，之后商家现金交易额次日自动到账银行卡！']);
        $is_have = Db::name('order')->where(['o_type'=>3,'o_shop_id'=>$shop_id,'o_tixian_status'=>1])->count();
        if($is_have > 0){
            return json(['status'=>100,'msg'=>'您有待审核提现']);
        }
        $shop = Db::name('shop')->where(['shop_id'=>$shop_id])->find();
        $conf = Db::name('jifen_conf')->where(['conf_id'=>['in','7,8,11']])->column ('conf_rate');
        if($shop['shop_wx_openid'] == ''){
            return json(['status'=>100,'msg'=>'请完善提现资料']);
        }
        if($shop['shop_balance'] <= 0){
            return json(['status'=>100,'msg'=>'可提现金额不足']);
        }
        if (preg_match('/\.\d{3,}/', $money)) {
            return json(['status'=>100,'msg'=>'小数点后最多只能两位']);
        }
        if($money > $shop['shop_balance']){
            return json(['status'=>100,'msg'=>'提现金额大于可提现金额']);
        }
        if($money < $conf[0]){
            return json(['status'=>100,'msg'=>'提现金额低于最低提现金额']);
        }
        if($shop['shop_balance'] < $conf[0]){
            return json(['status'=>100,'msg'=>'可提现金额低于最低提现金额']);
        }
		//----------超额判断（总额，一日500）-start---------
		$maxMoney = Db::name('order')
		->where(['o_type'=>3,'o_shop_id'=>$shop_id,'o_tixian_status'=>2,'o_pay_type'=>$type])
		->whereTime('o_add_time','today')
		->sum('o_money');
		if($maxMoney + $money > 5000) return json(['status'=>100,'msg'=>'每日总提现额度不得超过5000']);
		//-------------------end-----------------------------
        if($shop['shop_tixian_time'] < date('Y-m-d')){
            Db::name('shop')->where('shop_id',$shop_id)->update(['shop_tixian_money'=>0,'shop_edit_time'=>date('Y-m-d H:i:s')]);
        }
        $order = $this->getOrderNumber ();
        $new_money = $money - ($money * $conf[1]);
//        $new_money = floatval($new_money);
        $param = [
            'o_type'=>3,
            'o_order_num'=>$order,
            'o_money'=>$money,
            'o_pay_type'=>$type,
            'o_shop_id'=>$shop_id,
            'o_account'=>$type == 1 ? $shop['shop_ali_account'] : $shop['shop_wx_account'],
            'o_real_name'=>$shop['shop_user_name'],
            'o_add_time'=>date('Y-m-d H:i:s')
        ];
        $shop['shop_tixian_money'] = DB::name('shop')
                                    ->where(['shop_id'=>$shop_id])
                                    ->value('shop_tixian_money');
        if(($shop['shop_tixian_money'] + $money) >= $conf[2]){
            $param['o_tixian_status'] = 1;
            if($type == 2){
                $param['o_openid'] = $shop['shop_wx_openid'];
            }
            Db::name('order')->insert($param);
            return json(['status'=>200,'msg'=>'已达每日最大提现限额，等待后台审核']);
        }else {
            if($type == 1){
                $ali = new Ali();
                $res = $ali->tixianAgreeShopOrWork($order,$new_money,$shop['shop_ali_account'],$shop['shop_user_name']);
                $msg = '支付宝';
            }else{
                $wx = new Weixinshop();
                $res = $wx->userTiXian($order,$shop['shop_wx_openid'],$new_money,$shop['shop_user_name']);
                $msg = '微信';
            }

            if($res['status'] == 200){
                $param['o_tixian_status'] = 2;
                $param['o_pay_status'] = 2;
                $param['o_third_order_num'] = $res['msg'];

                Db::name('order')->insert($param);

                Db::name('shop')->where(['shop_id'=>$shop_id])->dec ('shop_balance',$money)->update(['shop_tixian_time'=>date('Y-m-d'),'shop_tixian_money'=>($shop['shop_tixian_money'] + $money)]);

                // Db::name('admin')->where('id',1)->setDec ('balance',$new_money);

                Db::name('notice')->insert (['n_to'=>2,'n_title'=>'余额提现','n_content'=>'您提现了'.$money.'元'."，已提现至您的{$msg}账户，请注意查收！",'n_images'=>'','n_type'=>1,'n_user_id'=>$shop_id,'n_read'=>',0,','n_delete'=>',0,','n_time'=>date('Y-m-d H:i:s')]);
                $this->jpushShop(1,$shop_id,'您提现了'.$money.'元'."，已提现至您的{$msg}账户，请注意查收！",json([]));
                return json(['status'=>200,'msg'=>"已提现至您的{$msg}账户，请注意查收！"]);
            }else{
                return json(['status'=>100,'msg'=>$res['msg']]);
            }
        }
    }


    public function unconfirmedBalance(){
        extract (input());
        $rate = Db::name('jifen_conf')->where('conf_id',2)->value('conf_rate');
        $data = Db::name('order o')
            ->join('order_info i','i.oi_order_id = o.o_id','left')
            ->where(['o_type'=>['in','1,2'],'o_status'=>['in','2,3,10'],'o_pay_status'=>2,'o_shop_id'=>$shop_id,'o_esp'=>1])
            ->order('o_add_time desc')
            ->page($page,10)
            ->select();
        if(!empty($data)){
            foreach($data as $key=>$vo){
                if($vo['o_esp'] == 1){
                    if($vo['oi_total_jifen'] > 0){
                        $data[$key]['oi_total_price'] = round($vo['oi_total_jifen'] * $rate + $vo['oi_total_price'] + $vo['o_postage'],2);
                    }
                    if($vo['o_postage'] > 0){
                        $data[$key]['oi_total_price'] = $vo['oi_total_price'] + $vo['o_postage'];
                    }
                }

                if($vo['o_esp'] == 2){
                    $data[$key]['oi_total_price'] = $vo['o_esp_money'];
                }

                $data[$key]['o_add_time'] = get_time (strtotime ($vo['o_add_time']));
            }
        }
        return json(['status'=>200,'msg'=>$data]);
    }


    public function getAgencyNum(){
        extract (input());
        $dai = Db::name('shop s')
            ->join('admin a','s.shop_superior_agent = a.id','left')
            ->where('shop_id',$shop_id)
            ->value('integral');
        $my = Db::name('shop')->where(['shop_id'=>$shop_id])->value('shop_integral');
        return json(['status'=>200,'msg'=>['dai'=>$dai,'my'=>$my]]);
    }



    public function cashPledge(){
        extract (input());
        return json(['status'=>100,'msg'=>'暂未开放！']);
        $dai = Db::name('shop s')
            ->join('admin a','s.shop_superior_agent = a.id','left')
            ->where('shop_id',$shop_id)
            ->field('id,integral,shop_balance')
            ->find();
        if($jifen > $dai['integral']){
            return json(['status'=>100,'msg'=>'代理积分池余额不足']);
        }
        if ($type == 3 && $money > $dai['shop_balance']) {
            return json(['status'=>100,'msg'=>'余额不足']);
        }
        $order = $this->getOrderNumber ();
        $param = [
            'o_type'=>4,
            'o_money'=>$money,
            'o_order_num'=>$order,
            'o_status'=>5,
            'o_pay_type'=>$type,
            'o_shop_id'=>$shop_id,
            'o_add_time'=>date('Y-m-d H:i:s'),
            'o_pay_status'=>1,
            'o_jifen'=>$jifen
        ];
        Db::name('order')->insert($param);
        if($type == 1){
            $ali = new Ali();
            $res = $ali->getParam($order,$money,'cashPledge','交押金');
        } else if ($type == 3) {
            // 余额支付
            Db::startTrans ();
            try {
                Db::name('order')->where('o_order_num', $order)->update(['o_pay_status'=>2]);
                Db::name('admin')->where('id', $dai['id'])->setDec('integral', $jifen);
                Db::name('shop')->where('shop_id', $shop_id)->setInc('shop_integral', $jifen);
                Db::name('shop')->where('shop_id', $shop_id)->setInc('shop_pledge_money', $money);
                Db::name('shop')->where('shop_id', $shop_id)->setDec('shop_balance', $money);
                Db::commit ();
                return json(['status'=>200,'msg'=>'支付成功']);
            }catch (\Exception $e){
                Db::rollback ();
            }
        } else {
            $wx = new Weixinshop();
            // $money = 0.01;//Todo
            $obj = [
                'attach'=>"cashPledge",
                'body'=>"交押金",
                'total_fee'=>$money * 100,
                'out_trade_no'=>$order,
                'product_id'=>"",
                'trade_type'=>"APP"
            ];
            $res = $wx->WeChatPayReady($obj);
        }
        return json(['status'=>200,'msg'=>$res]);
    }



    public function cashPledgeList(){
        extract (input());
        $data = Db::name('order o')
            ->join('shop s','s.shop_id = o.o_shop_id','left')
            ->where(['o_type'=>['in','4,5,7'],'o_shop_id'=>$shop_id, 'o_pay_status'=>2])
            ->order('o_add_time desc')
            ->page($page,10)
            ->select ();
        if(!empty($data)){
            $rat = Db::name('jifen_conf')->where('conf_id',1)->value('conf_rate');
            foreach($data as $key=>$vo){
                $data[$key]['o_add_time'] = get_time(strtotime ($vo['o_add_time']));
                if($vo['o_type'] == 7){
                    $data[$key]['o_money'] = $vo['o_jifen'] * $rat;
                }
            }
        }
        return json(['status'=>200,'msg'=>$data]);
    }


    public function depositRefund(){
        extract (input());
        return json(['status'=>100,'msg'=>'暂未开放！']);
        $rate = Db::name('jifen_conf')->where('conf_id',1)->value('conf_rate');
        $service = Db::name('jifen_conf')->where('conf_id',8)->value('conf_rate');
        $shop = Db::name('shop')->where('shop_id',$shop_id)->find();
        $integral = $shop['shop_integral'];
        if($shop['shop_wx_openid'] == ''){
            return json(['status'=>100,'msg'=>'请完善提现资料']);
        }
        if($integral <= 0){
            return json(['status'=>100,'msg'=>'无可退押金']);
        }
        $pledge_money = $integral * $rate;
        if($money > $pledge_money){
            return json(['status'=>100,'msg'=>'可退押金不足']);
        }
        $new_money = round($money - ($money * $service),2);
        $number = $this->getOrderNumber ();
        $back = $money/$rate;
        $param = [
            'o_type'=>5,
            'o_shop_id'=>$shop_id,
            'o_order_num'=>$number,
            'o_pay_type'=>$type,
            'o_money'=>$money,
            'o_jifen'=>$back,
            'o_account'=>$type == 1 ? $shop['shop_ali_account'] : $shop['shop_wx_account'],
            'o_real_name'=>$shop['shop_user_name'],
            'o_add_time'=>date('Y-m-d H:i:s')
        ];
        if($type == 1){
            $ali = new Ali();
            $res = $ali->tixianAgreeShopOrWork($number,$new_money,$shop['shop_ali_account'],$shop['shop_user_name']);
        }else{
            if($type == 2){
                $param['o_openid'] = $shop['shop_wx_openid'];
            }
            $wx = new Weixinshop();
            $res = $wx->userTiXian($number,$shop['shop_wx_openid'],$new_money,$shop['shop_user_name']);
        }
        if($res['status'] == 200){
            $param['o_tixian_status'] = 2;
            $param['o_pay_status'] = 2;
            $param['o_third_order_num'] = $res['msg'];
            Db::name('order')->insert($param);
            Db::name('admin')->where('id',$shop['shop_superior_agent'])->setInc('integral',$back);
            Db::name('shop')->where('shop_id',$shop_id)->dec('shop_pledge_money',$money)->dec('shop_integral',$back)->update();

            Db::name('notice')->insert (['n_to'=>2,'n_title'=>'退押金','n_content'=>'您退押金'.$money.'元','n_images'=>'','n_type'=>1,'n_user_id'=>$shop_id,'n_read'=>',0,','n_delete'=>',0,','n_time'=>date('Y-m-d H:i:s')]);
            $this->jpushShop(1,$shop_id,'您退押金了'.$money.'元',json([]));
            return json(['status'=>200,'msg'=>'押金退还成功']);
        }else{
            return json(['status'=>100,'msg'=>$res['msg']]);
        }
    }




    public function faceToFace(){
        extract (input());
        $jifen = Db::name('shop')->where('shop_id',$shop_id)->value('shop_integral');
        if($num > $jifen){
            return json(['status'=>100,'msg'=>'积分余额不足，请充值']);
        }
        $id = Db::name('qrcode')->insertGetId(['qr_shop_id'=>$shop_id,'qr_num'=>$num,'qr_lose_time'=>date('Y-m-d H:i:s',strtotime ('+1 day'))]);
        $link = http_type ()."/api/user/getQrcodeJifen?id={$id}";
        return json(['status'=>200,'msg'=>$link]);
    }



    public function giveJifen(){
        extract (input());
        $arr = Db::name('u_user')->where('user_phone',$phone)->find();
        if(empty($arr)){
            return json(['status'=>100,'msg'=>'赠送账户不存在']);
        }
        $jifen = Db::name('shop')->where('shop_id',$shop_id)->find();
        if($num > $jifen['shop_integral']){
            return json(['status'=>100,'msg'=>'积分余额不足']);
        }
        if ($jifen['shop_account'] == '13305504411' || $jifen['shop_account'] == '18110767086') {
            return json(['status'=>100,'msg'=>'赠送积分错误']);
        }
        Db::startTrans ();
        try{
            $rat = Db::name('jifen_conf')->where('conf_id',1)->value('conf_rate');
            Db::name('shop')->where('shop_id',$shop_id)->dec('shop_integral',$num)->dec('shop_pledge_money',$num*$rat)->update();
            $this->jifenFlow ($num,$jifen['shop_qu_id'],$arr['user_id'],'giveJifen');

            Db::name('notice')->insert (['n_to'=>1,'n_title'=>'积分赠送','n_content'=>$jifen['shop_name']."赠送你{$num}积分",'n_images'=>'','n_type'=>3,'n_user_id'=>$arr['user_id'],'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s')]);
            try {
                $this->jpushUser(1,$arr['user_id'],$jifen['shop_name']."赠送你{$num}积分",json([]));
            } catch (\Exception $e) {}
            Db::name('jifen_consume')->insert(['consume_content'=>$jifen['shop_name']."赠送你{$num}积分",'consume_user_id'=>$arr['user_id'],'consume_add_time'=>date('Y-m-d H:i:s')]);

            Db::name('order')->insert(['o_type'=>7,'o_order_num'=>$this->getOrderNumber (),'o_jifen'=>$num,'o_status'=>5,'o_pay_status'=>2,'o_shop_id'=>$shop_id,'o_user_id'=>$arr['user_id'],'o_add_time'=>date('Y-m-d H:i:s')]);
            Db::commit ();
            return json(['status'=>200,'msg'=>'赠送成功']);
        }catch (\Exception $e){
            Db::rollback ();
            return json(['status'=>100,'msg'=>'赠送失败']);
        }
    }



    // public function myJifenOldNOUSE(){
        // extract (input ());
        // $data = Db::name('order')
            // ->where(['o_type'=>['in','4,5,6,7'],'o_shop_id'=>$shop_id, 'o_jifen'=>['>', 0], 'o_pay_status'=>2])
            // ->field ('o_id,o_type,o_order_num,o_jifen,o_shop_id,o_add_time')
            // ->order('o_add_time desc')
            // ->page($page,10)
            // ->select ();
        // if(!empty($data)){
            // foreach($data as $key=>$vo){
                // $data[$key]['o_add_time'] = get_time (strtotime ($vo['o_add_time']));
            // }
        // }
        // $record_arr = DB::name('record')
                    // ->where(['record_shop_id'=>$shop_id,'record_type'=>['in', [1,3]],'record_status'=>2,'record_give_jifen'=>['>',0]])
                    // ->field('record_id as o_id,record_number as o_order_num,record_give_jifen as o_jifen,record_shop_id as o_shop_id,record_pay_time as o_add_time')
                    // ->order('record_pay_time desc')
					// ->select();
        // if (!empty($record_arr)) {
            // foreach ($record_arr as $k => $v) {
                // $record_arr[$k]['o_type'] = -1;
                // $record_arr[$k]['o_add_time'] = get_time (strtotime ($v['o_add_time']));
            // }
            // $data = array_merge($data,$record_arr);
            // // 对二维数组排序
            // foreach ($data as $key=>$value){
                // $addtime[$key] = $value['o_add_time'];
            // }
            // array_multisort($addtime,SORT_DESC,$data);
        // }
        // return json(['status'=>200,'msg'=>$data]);
    // }
	public function myJifen(){
        extract (input ());
        $data = Db::name('order')
            ->where(['o_type'=>['in','4,5,6,7'],'o_shop_id'=>$shop_id, 'o_jifen'=>['>', 0], 'o_pay_status'=>2])
            ->field ('o_id,o_type,o_order_num,o_jifen,o_shop_id,o_add_time')
            ->order('o_add_time desc')
            ->page($page,10)
            ->select ();
			
        // if(!empty($data)){
            // foreach($data as $key=>$vo){
                // $data[$key]['o_add_time'] = get_time (strtotime ($vo['o_add_time']));
            // }
        // }
        $record_arr = DB::name('record')
                    ->where(['record_shop_id'=>$shop_id,'record_type'=>['in', [1,3]],'record_status'=>2,'record_give_jifen'=>['>',0]])
                    ->field('record_id as o_id,record_number as o_order_num,record_give_jifen as o_jifen,record_shop_id as o_shop_id,record_pay_time as o_add_time')
                    ->order('record_pay_time desc')
					->select();
        if (!empty($record_arr)) {
            foreach ($record_arr as $k => $v) {
                $record_arr[$k]['o_type'] = -1;
                // $record_arr[$k]['o_add_time'] = get_time (strtotime ($v['o_add_time']));
            }
            $data = array_merge($data,$record_arr);
            // 对二维数组排序
            foreach ($data as $key=>$value){
                $addtime[$key] = $value['o_add_time'];
            }
            array_multisort($addtime,SORT_DESC,$data);
        }
		if(!empty($data)){
            foreach($data as $key=>$vo){
                $data[$key]['o_add_time'] = get_time (strtotime ($vo['o_add_time']));
            }
        }
        return json(['status'=>200,'msg'=>$data]);
    }



    public function shopInfo(){
        extract (input());
        $data = Db::name('shop s')
            ->join('admin a','s.shop_superior_agent = a.id','left')
            ->join('area e','a.area = e.district_id','left')
            ->where('shop_id',$shop_id)
            ->field("s.*,CONCAT(e.district,'代理-',a.phone) username,shop_lon,shop_lat")
            ->find();
        if(!empty($data) && !$data['shop_link']){
            $data['shop_link'] = "";
        }
        return json(['status'=>200,'msg'=>$data]);
    }



    public function shopFeedBack(){
        extract (input());
        $area = Db::name('shop')->where('shop_id',$shop_id)->value('shop_qu_id');
        $param = [
            'f_type'=>2,
            'f_content'=>$content,
            'f_images'=>$images,
            'f_user_id'=>$shop_id,
            'f_area'=>$area,
            'f_add_time'=>date("Y-m-d H:i:s")
        ];
        $res = Db::name('feedback')->insert($param);
        if($res){
            return json(['status'=>200,'msg'=>'反馈成功']);
        }else{
            return json(['status'=>100,'msg'=>'反馈失败']);
        }
    }


    public function buyInfo(){
        extract (input());
        $info = Db::name('order o')
            ->join('u_user u','o.o_user_id = u.user_id','left')
            ->where('o_id',$o_id)
            ->find();
        return json(['status'=>200,'msg'=>$info]);
    }



    public function getMoneyOrder(){
        extract(input());
        $where = [
            'o_type'=>2,
            'o_shop_id'=>$shop_id
        ];
        switch($type){
            case 1:
                $where['o_status'] = 2;
                break;
            case 2:
                $where['o_status'] = 3;
                break;
            case 3:
                $where['o_status'] = ['in','4,5'];
                break;
            case 4:
                $where['o_status'] = 10;
                break;
        }
        $data = Db::name('order')
            ->where($where)
            ->field(['o_id','o_order_num','o_money','o_shop_name','o_cate','o_m_type'])
            ->page($page,10)
            ->order('o_add_time desc')
            ->select();
        if(!empty($data)){
            foreach($data as $key=>$vo){
                $info = Db::name('order_info')
                    ->where('oi_order_id',$vo['o_id'])
                    ->field(['oi_order_id','oi_goods_id','oi_goods_name','oi_goods_image','oi_goods_price','oi_num', 'oi_goods_model'])
                    ->select();
                $data[$key]['info'] = $info;
            }
        }
        return json(['status'=>200,'msg'=>$data]);
    }


    public function goDeliverGoods(){
        extract (input());
        Db::startTrans ();
        try{
            if(!$express_num){
                return json(['status'=>100,'msg'=>'请手动输入物流订单号']);
            }
            $order = Db::name('order')->where('o_id',$o_id)->find();
            $shop = Db::name('shop')->where('shop_id',$shop_id)->find();
            if($order['o_type'] == 2){
                $all = Db::name('order')->where(['o_type'=>2,'o_shop_id'=>$shop_id,'o_status'=>['in','2,3'],'o_esp'=>1])->select ();
                $must = 0;
                if(!empty($all)){
                    foreach($all as $vv){
                        $pro = Db::name('order_info')->where('oi_order_id',$vv['o_id'])->select();
                        foreach($pro as $z){
                            $give = Db::name('product')->where(['p_id'=>$z['oi_goods_id']])->value('p_give');
                            $must = $must + ($give * $z['oi_num']);
                        }
                    }
                }
//                if($shop['shop_integral'] < $must){
//                    Db::name('notice')->insert (['n_to'=>2,'n_title'=>'系统消息','n_content'=>'积分押金不足，不可发货，请尽快充值押金','n_images'=>'','n_type'=>1,'n_user_id'=>$shop_id,'n_read'=>',0,','n_delete'=>',0,','n_time'=>date('Y-m-d H:i:s')]);
//                    $this->jpushShop(1,$shop_id,'积分押金不足，不可发货，请尽快充值押金',json([]));
//
//                    return json(['status'=>100,'msg'=>'积分押金不足，不可发货']);
//                }
            }
            Db::name('order')
                ->where('o_id',$o_id)
                ->update(['o_express'=>$express,'o_express_code'=>$express_code,'o_express_num'=>$express_num,'o_status'=>3,'o_express_time'=>date('Y-m-d H:i:s')]);

            $param = [
                'n_to'=>1,
                'n_title'=>'物流信息',
                'n_content'=> "你购买的商品已发货了！",
                'n_type'=>2,
                'n_user_id'=>$order['o_user_id'],
                'n_read'=>1,
                'n_delete'=>1,
                'n_time'=>date('Y-m-d H:i:s')
            ];
            Db::name('notice')->insert($param);
            try{
                $this->jpushUser(1,$order['o_user_id'],"你购买的商品已发货了！",json([]));
            }catch (\Exception $e){
                
            }
            Db::commit ();
            return json(['status'=>200,'msg'=>'发货成功']);
        }catch (\Exception $e){
            Db::rollback ();
            return json(['status'=>100,'msg'=>'发货失败']);
        }
    }


    public function scanQrcodeOrder(){
        extract (input());
        if (!isset($side)) {
            return '请用支分宝商家设备扫码';
        }
        if($side == 1){
            return json(['status'=>100,'msg'=>'不可扫描']);
        }
        $data = Db::name('order')
            ->where(['o_order_num'=>$num])
            ->find();
        if($data['o_shop_id'] != $shop_id){
            return json(['status'=>100,'msg'=>'不可扫描']);
        }
        if(!empty($data)){
            $info = Db::name('order_info')
                ->where('oi_order_id',$data['o_id'])
                ->field(['oi_order_id','oi_goods_id','oi_goods_name','oi_goods_image','oi_goods_price','oi_goods_jifen','oi_goods_model','oi_num'])
                ->select();
            $data['info'] = $info;
        }
        return json(['status'=>200,'msg'=>$data]);
    }



    public function exchange(){
        extract (input());
        $order = Db::name('order')->where(['o_id'=>$o_id])->find();
        if($order['o_status'] != 10){
            return json(['status'=>100,'msg'=>'商品已兑换']);
        }
        Db::startTrans ();
        try{
            Db::name('order')->where(['o_id'=>$o_id])->setField ('o_status',4);
            if($order['o_esp'] == 1){
                $order_info = Db::name('order_info')->where('oi_order_id',$order['o_id'])->select ();
                $rat = Db::name('jifen_conf')->where('conf_id',1)->value('conf_rate');
                $redYajinAll = 0;
                foreach($order_info as $ss){
                    $give = Db::name('product')->where('p_id',$ss['oi_goods_id'])->find();
                    if($give['p_give'] > 0){
                        $qu = Db::name('shop')->where('shop_id',$give['p_shop_id'])->value('shop_qu_id');
                        Db::name('admin')->where('area',$qu)->setDec('integral',$give['p_give']);
                        $redYajin = ($give['p_give'] * $ss['oi_num']) * $rat;
                        $redYajinAll += $redYajin;
//                        Db::name('shop')->where('shop_id',$give['p_shop_id'])->dec('shop_integral',$give['p_give'] * $ss['oi_num'])->dec('shop_pledge_money',($give['p_give'] * $ss['oi_num'])*$rat)->update();
//
//                        Db::name('order')->insert(['o_type'=>5,'o_order_num'=>$this->getOrderNumber (),'o_money'=>($give['p_give'] * $ss['oi_num'])*$rat,'o_jifen'=>'','o_status'=>5,'o_pay_status'=>2,'o_shop_id'=>$give['p_shop_id'],'o_add_time'=>date('Y-m-d H:i:s')]);

                        $this->jifenFlow($give['p_give']* $ss['oi_num'],$qu,$order['o_user_id'],'exchange');

                        Db::name('jifen_consume')->insert(['consume_content'=>'购买商品赠送'.$give['p_give'] * $ss['oi_num'].'积分','consume_user_id'=>$order['o_user_id'],'consume_add_time'=>date('Y-m-d H:i:s')]);
                        Db::name('notice')->insert (['n_to'=>1,'n_title'=>'购买商品','n_content'=>'购买商品赠送'.$give['p_give'] * $ss['oi_num'].'积分','n_images'=>'','n_type'=>2,'n_user_id'=>$order['o_user_id'],'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s')]);
                        try {
                            $this->jpushUser(1,$order['o_user_id'],'购买商品赠送'.$give['p_give'] * $ss['oi_num'].'积分',json([]));
                        } catch (\Exception $e) {}
                    }
                }
                if($order['o_money'] > 0){
                    if($redYajinAll > 0){
                        Db::name('order')->where(['o_id' => $o_id])->setField('o_m_yajin', $redYajinAll);
                    }
                    Db::name('shop')->where('shop_id',$order['o_shop_id'])->setInc ('shop_balance',$order['o_money'] - $order['o_m_money']-$redYajinAll);
                    Db::name('shop')->where('shop_id',$order['o_shop_id'])->setInc ('shop_all_balance',$order['o_money'] - $order['o_m_money']-$redYajinAll);
                    shopjiluerror($order['o_shop_id'],$order['o_money'] - $order['o_m_money']-$redYajinAll,5);
                    Db::name('shop')->where('shop_id',$order['o_shop_id'])->setDec ('shop_balance_yet',$order['o_money'] - $order['o_m_money']);

                    // 店铺现金交易额
                    Db::name('shop')->where('shop_id',$order['o_shop_id'])->setInc ('shop_money_balance',$order['o_money'] - $order['o_m_money']);
                    // 店铺当日现金交易额// 定时任务，每日0点清空
                    DB::name('shop')->where('shop_id',$order['o_shop_id'])->setInc ('shop_today_balance',$order['o_money'] - $order['o_m_money']);
                    // 店铺现金交易1‰分红
                    $shop_user_id   = DB::name('shop')
                                    ->where('shop_id',$order['o_shop_id'])
                                    ->value('shop_user_id');
                    $this->shop_profit($order['o_shop_id'],$shop_user_id,$order['o_money'],3);

                    // Db::name('admin')->where('id',1)->setDec ('balance',$order['o_money']);
                }
                if($order['o_jifen'] > 0){
                    $rat = Db::name('jifen_conf')->where('conf_id',2)->value('conf_rate');
                    Db::name('shop')->where('shop_id',$order['o_shop_id'])->setDec ('shop_balance_yet',$order['o_jifen'] * $rat);
                    Db::name('shop')->where('shop_id',$order['o_shop_id'])->setInc('shop_balance',$order['o_jifen'] * $rat);
                    Db::name('shop')->where('shop_id',$order['o_shop_id'])->setInc('shop_all_balance',$order['o_jifen'] * $rat);
                    shopjiluerror($order['o_shop_id'],$order['o_jifen'] * $rat,6);
                }
                try {
                    $this->jpushShop(1,$order['o_shop_id'],"兑换成功",['type2' => 1024,'msg' => "兑换成功"]);
                } catch (\Exception $e) {}
            }else if($order['o_esp'] == 2){
                Db::name('shop')->where('shop_id',$order['o_shop_id'])->setInc ('shop_balance',$order['o_esp_money']);
                Db::name('shop')->where('shop_id',$order['o_shop_id'])->setInc ('shop_all_balance',$order['o_esp_money']);
                shopjiluerror($order['o_shop_id'],$order['o_esp_money'],7);
                Db::name('shop')->where('shop_id',$order['o_shop_id'])->setDec ('shop_balance_yet',$order['o_esp_money']);
                // 店铺现金交易额
                Db::name('shop')->where('shop_id',$order['o_shop_id'])->setInc ('shop_money_balance',$order['o_esp_money']);
                // 店铺当日现金交易额// 定时任务，每日0点清空
                DB::name('shop')->where('shop_id',$order['o_shop_id'])->setInc ('shop_today_balance',$order['o_esp_money']);
                // 店铺现金交易1‰分红
                $shop_user_id   = DB::name('shop')
                                ->where('shop_id',$order['o_shop_id'])
                                ->value('shop_user_id');
                $this->shop_profit($order['o_shop_id'],$shop_user_id,$order['o_esp_money'],3);
            }
//---------------------------------产品池分佣结算 start ---------------------------------------------
            if($order['o_m_type'] == 2){
                $pool = Db::name('m_record')
                    ->where('record_order_number',$order['o_order_num'])
                    ->where('record_from_type','in','4,3,7,8')
                    ->select();
                if($pool){
                    if($order['o_m_user_id'] && $order['o_m_user_id'] > 0){
                        $qu = Db::name('u_user')->where('user_id',$order['o_m_user_id'])->value('user_area');
                    }
                    foreach ($pool as $k => $v){
                        if($v['record_money'] > 0){
                            Db::name('u_user')->where('user_id',$v['record_user_id'])->setInc('user_m_pool_money',$v['record_money']);
                        }
                        if($v['record_jifen'] > 0){
                            $this->jifenFlow($v['record_jifen'],$qu,$v['record_user_id'],'poolFenYong');
                            $quname = Db::name('area')->where('district_id',$qu)->value('district');
                            $cc = [
                                '3' => '用户购买'.$give['p_name'].'商品返佣',
                                '4' => '用户购买'.$give['p_name'].'商品返佣',
                                '7' => $give['p_name'].'商品团团赚团长奖励',
                                '8' => $give['p_name'].'商品参与团团赚奖励',
                            ];
                            Db::name('jifen_consume')->insert(['consume_content'=>$cc[$v['record_from_type']].$v['record_jifen']."积分({$quname})",'consume_user_id'=>$v['record_user_id'],'consume_add_time'=>date('Y-m-d H:i:s')]);
                        }
                        //推送待定
//                        Db::name('jifen_consume')->insert(['consume_content'=>'购买产品池'.$give['p_name'].'商品赠送'.$give['p_give'] * $ss['oi_num'].'积分','consume_user_id'=>$order['o_user_id'],'consume_add_time'=>date('Y-m-d H:i:s')]);
//                        Db::name('notice')->insert (['n_to'=>1,'n_title'=>'购买商品','n_content'=>'购买'.$give['p_name'].'商品赠送'.$give['p_give'] * $ss['oi_num'].'积分','n_images'=>'','n_type'=>2,'n_user_id'=>$order['o_user_id'],'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s')]);
//                        $this->jpushUser(1,$order['o_user_id'],'购买'.$give['p_name'].'商品赠送'.$give['p_give'] * $ss['oi_num'].'积分',json([]));
                    }
                }
                Db::name('m_record')->where('record_order_number',$order['o_order_num'])->update([
                    'record_status' => 2,
                    'record_sure_time' => date('Y-m-d H:i:s')
                ]);
            }
            //---------------------------------产品池分佣结算 end ---------------------------------------------
            Db::name('notice')->insert (['n_to'=>1,'n_title'=>'购物订单','n_content'=>'订单兑换，等待买家评价','n_images'=>'','n_type'=>2,'n_user_id'=>$order['o_user_id'],'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s')]);
            try {
                $this->jpushUser(1,$order['o_user_id'],'订单订单兑换，等待买家评价~~',json([]));
            } catch (\Exception $e) {}
            Db::commit ();
            return json(['status'=>200,'msg'=>'兑换成功']);
        }catch (\Exception $e){
            Db::rollback ();
            return json(['status'=>100,'msg'=>'兑换失败']);
        }
    }


    public function getOStatus(){
        extract (input());
        $status = Db::name('order')->where(['o_id'=>$o_id])->value ('o_status');
        return json(['status'=>200,'msg'=>$status]);
    }


    public function getJifenOrder(){
        extract(input());
        $where = [
            'o_type'=>1,
            'o_shop_id'=>$shop_id
        ];
        switch($type){
            case 1:
                $where['o_status'] = 2;
                break;
            case 2:
                $where['o_status'] = 3;
                break;
            case 3:
                $where['o_status'] = 10;
                break;
            case 4:
                $where['o_status'] = ['in','4,5'];
                break;
        }
        $data = Db::name('order')
            ->where($where)
            ->field(['o_id','o_order_num','o_money','o_jifen','o_shop_name','o_cate'])
            ->page($page,10)
            ->order('o_add_time desc')
            ->select();
        if(!empty($data)){
            foreach($data as $key=>$vo){
                $info = Db::name('order_info')
                    ->where('oi_order_id',$vo['o_id'])
                    ->field(['oi_order_id','oi_goods_id','oi_goods_name','oi_goods_image','oi_goods_price','oi_goods_jifen','oi_num', 'oi_goods_model'])
                    ->select();
                $data[$key]['info'] = $info;
            }
        }
        return json(['status'=>200,'msg'=>$data]);
    }



    public function refundOrder(){
        extract (input());
        $where = [
            'o_shop_id'=>$shop_id,
            'o_status'=>['in','6,11']
        ];
        switch ($type){
            case 1:
                $where['o_refund'] = 1;
                break;
            case 2:
                $where['o_refund'] = 2;
                break;
            case 3:
                $where['o_refund'] = 3;
                break;
        }
        $data = Db::name('order')
            ->where($where)
            ->field(['o_id','o_type','o_order_num','o_money','o_jifen','o_shop_name','o_cate','o_refund_time','o_user_id'])
            ->page($page,10)
            ->order('o_add_time desc')
            ->select();
        if(!empty($data)){
            foreach($data as $key=>$vo){
                $info = Db::name('order_info')
                    ->where('oi_order_id',$vo['o_id'])
                    ->field(['oi_order_id','oi_goods_id','oi_goods_name','oi_goods_image','oi_goods_price','oi_goods_jifen','oi_num'])
                    ->select();
                $data[$key]['info'] = $info;
            }
        }
        return json(['status'=>200,'msg'=>$data]);
    }



    public function disposeRefundOrder(){
        extract (input());
        Db::startTrans ();
        try{
            $order = Db::name('order')->where('o_id',$o_id)->find ();
            if($sta == 2){
                $msg = '同意';
            }else if($sta == 4){
                $msg = '驳回';
            }
            Db::name('notice')->insert (['n_to'=>1,'n_title'=>'购物订单','n_content'=>"订单退款\退货,商户{$msg}",'n_images'=>'','n_type'=>2,'n_user_id'=>$order['o_user_id'],'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s')]);
            try {
                $this->jpushUser(1,$order['o_user_id'],"订单退款\退货,商户{$msg}",json([]));
            } catch (\Exception $e) {}
            Db::name('notice')->insert (['n_to'=>2,'n_title'=>'购物订单','n_content'=>"订单退款\退货,商户{$msg}",'n_images'=>'','n_type'=>2,'n_user_id'=>$order['o_shop_id'],'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s')]);
            $this->jpushShop(1,$order['o_shop_id'],"订单退款\退货,商户{$msg}",json([]));

            if($sta == 4){
                if($order['o_cate'] == 2 || $order['o_cate'] == 4){
                    $o_status = 10;
                }else{
                    $o_status = 3;
                }
                Db::name('order')->where('o_id',$o_id)->setField ('o_status',$o_status);
            }
            Db::name('order')->where('o_id',$o_id)->setField ('o_refund',$sta);
            Db::commit ();
            return json(['status'=>200,'msg'=>'操作成功']);
        }catch (\Exception $e){
            Db::rollback ();
            return json(['status'=>100,'msg'=>'操作失败']);
        }
    }


    public function payRefundOrder(){
        extract (input());
        $order = Db::name('order')->where('o_id',$o_id)->find();
        Db::startTrans ();
        try{
            if($order['o_pay_type'] == 1){
                $ali = new Ali();
                $res = $ali->refund($order['o_third_order_num'],$order['o_money']);
                if($res['status'] == 100){
                    return json($res);
                }
            }else if($order['o_pay_type'] == 2){
                $wx = new Weixin();
                $res = $wx->weixiReturn($order['o_money'],$order['o_money'],$order['o_third_order_num'],$this->getOrderNumber ());
                if($res['status'] == 100){
                    return json($res);
                }
            }
                // Db::name('admin')->where('id',1)->setDec ('balance',$order['o_money']);
                Db::name('order')->where('o_id',$o_id)->setField ('o_refund',3);
                Db::name('shop')->where('shop_id',$order['o_shop_id'])->setDec ('shop_balance_yet',$order['o_money']-$order['o_m_money']);

            Db::name('notice')->insert (['n_to'=>1,'n_title'=>'购物订单','n_content'=>'订单退款\退货成功','n_images'=>'','n_type'=>2,'n_user_id'=>$order['o_user_id'],'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s')]);
            try {
                $this->jpushUser(1,$order['o_user_id'],'订单退款\退货成功',json([]));
            } catch (\Exception $e) {}
            Db::name('notice')->insert (['n_to'=>2,'n_title'=>'购物订单','n_content'=>'订单退款\退货成功','n_images'=>'','n_type'=>2,'n_user_id'=>$order['o_shop_id'],'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s')]);
            $this->jpushShop(1,$order['o_shop_id'],'订单退款\退货成功',json([]));
            Db::commit ();
            return json(['status'=>200,'msg'=>'退款成功']);
        }catch (\Exception $e){
            Db::rollback ();
            return json(['status'=>100,'msg'=>'退款失败']);
        }
    }


    public function getNoticeData(){
        extract (input());
        $data['system'] = $this->getNotice(1,2,$shop_id);
        $data['order'] = $this->getNotice(2,2,$shop_id);
        $data['active'] = $this->getNotice(4,2,$shop_id);
        $data['win'] = $this->getNotice(5,2,$shop_id);
        return json(['status'=>200,'msg'=>$data]);
    }



    public function getNotice($type,$to,$shop_id = ''){
        $where = ['n_to'=>$to,'n_type'=>$type];
        if($shop_id){
            $where['n_user_id'] = $shop_id;
        }
        if(in_array($type,[1,4])){
            $where['n_delete'] = ['not like', "%," . $shop_id . ",%"];
            $last = Db::name('notice')->where($where)->order('n_time desc')->find();
            $count = Db::query("SELECT COUNT(*) AS tp_count FROM `up_notice` WHERE  (`n_to` = {$to}  AND `n_type` = {$type}  AND `n_delete` NOT LIKE '%,{$shop_id},%'  AND `n_read` NOT LIKE '%,{$shop_id},%' AND `n_user_id` = '') OR (  `n_to` = {$to}  AND `n_type` = {$type}  AND `n_delete` NOT LIKE '%,{$shop_id},%'  AND `n_read` NOT LIKE '%,{$shop_id},%' AND  n_user_id = {$shop_id} ) LIMIT 1");
            $count = $count[0]['tp_count'];
        }elseif(in_array($type,[2,3,5])){
            $where['n_delete'] = 1;
            $last = Db::name('notice')->where($where)->order('n_time desc')->find();
            $where['n_read'] = 1;
            $count = Db::name('notice')->where($where)->count();
        }
        if($count > 99){
            $count = 99;
        }
        $data = [
            'count'=>$count,
            'title' => $last['n_title'] ? $last['n_title'] : '',
            'time' => $last['n_time'] ? $last['n_time'] : ''
        ];
        return $data;
    }


    public function getNoticeList(){
        extract (input());
        $where = [
            'n_to'=>2,
            'n_type'=>$type
        ];
        if(in_array ($type,[1,4])){
            $where['n_delete'] = ['not like', "%," . $shop_id . ",%"];
            $map  = "n_user_id = '' OR n_user_id = ".$shop_id;
        }elseif(in_array($type,[2,5])){
            $where['n_user_id'] = $shop_id;
            $where['n_delete'] = 1;
            $map = '';
        }
        $data = Db::name('notice')
            ->where($where)
            ->where($map)
            ->order('n_time desc')
            ->page($page,10)
            ->select();
        if(!empty($data)){
            foreach($data as $key=>$vo){
                if(in_array ($vo['n_type'],[1,4]) && $vo['n_user_id'] == ''){
                    $n_read = trim(',',$vo['n_read']);
                    if(in_array ($shop_id,explode (',',$n_read))){
                        $data[$key]['n_read'] = 2;
                    }else{
                        $data[$key]['n_read'] = 1;
                    }
                }
            }
        }
        return json(['status'=>200,'msg'=>$data]);
    }

    public function jifenTreasure(){
        extract(input());
        $param = [
            'd_shop_id'=>$shop_id,
            'd_product_id'=>$goods_id,
            'd_equity'=>$equity,
            'd_price'=>$price,
            'd_stock'=>$stock,
            'd_model'=>$model,
            'd_send_type'=>$send,
            'd_join_integral'=>$jifen,
            'd_join_num'=>$man,
            'd_type'=>$type,
            'd_start_time'=>$start_time,
            'd_end_time'=>$end_time
        ];
        $res = Db::name('d_treasure')->insert($param);
        if($res){
            return json(['status'=>200,'msg'=>'发布成功']);
        }else{
            return json(['status'=>100,'msg'=>'发布失败']);
        }
    }


    public function getActiveLists(){
        extract (input());
        if($type == 1){
            $data = Db::name('product')
                ->where(['p_shop_id'=>$shop_id,'p_type'=>['in','2,3']])
                ->whereTime ('p_end_time','>',date('Y-m-d H:i:s'))
                ->page($page,10)
                ->order('p_end_time desc')
                ->select ();
            if(!empty($data)){
                foreach($data as $key=>$vo){
                    if($vo['p_model'] == 2){
                        $data[$key]['p_stock_num'] = Db::name('product_model')->where('m_product_id',$vo['p_id'])->sum('m_num');
                    }
                }
            }
        }else{
            $data = Db::name('d_treasure d')
                ->join('product p','p.p_id = d.d_product_id','left')
                ->where(['d_shop_id'=>$shop_id,'d_status'=>['neq',6]])
                ->page($page,10)
                ->order('d_end_time desc')
                ->select ();
        }
        return json(['status'=>200,'msg'=>$data]);
    }

   
    public function getAd(){
        extract (input());
        $shop = Db::name('shop')->where('shop_id',$shop_id)->find();
        $ad = Db::name('ad')->where(['ad_qu_id'=>$shop['shop_qu_id'],'ad_type'=>2,'ad_port'=>2])->select();
        if(empty($ad)){
            $ad = Db::name('ad')->where(['ad_type'=>1,'ad_port'=>2])->select();
        }
        return json(['status'=>200,'msg'=>$ad]);
    }


    /*******************************************二次开发******************************************/
    public function getQRCode(){
        extract (input());
        $QRCode = Db::name('shop')->where(['shop_id'=>$shop_id])->value('shop_qr_code');
        if($QRCode){
            return json(['code'=>200,'msg'=>$QRCode]);
        }else{
            $encrypt = $this->encrypt($shop_id,'ENCODE');
            $url = Qrcode(http_type ()."/api/user/collection?id={$encrypt}");
            if(!$url){
                return json(['code'=>100,'msg'=>'收款码生成失败']);
            }
            $suffix = pathinfo($url, PATHINFO_EXTENSION);
            $key = md5(time().uuid()).'.'.$suffix;
            $up = new \aliyun\OssDemo();
            $data = $up->uploadFile(ROOT_PATH . 'public' . $url,$key);
            if(!$data){
                return json(['code'=>100,'msg'=>'收款码生成失败']);
            }
            $place = "https://jintianjifen.oss-cn-shanghai.aliyuncs.com/".$data;
            if(file_exists (ROOT_PATH . 'public' . $url)){
                unlink (ROOT_PATH . 'public' . $url);
            }
            Db::name('shop')->where(['shop_id'=>$shop_id])->setField ('shop_qr_code',$place);
            return json(['code'=>200,'msg'=>$place]);
        }
    }
    public function getQRCodeForAdmin($shop_id){
        $QRCode = Db::name('shop')->where(['shop_id'=>$shop_id])->value('shop_qr_code');
        if($QRCode){
            return ['code'=>200,'msg'=>$QRCode];
        }else{
            $encrypt = $this->encrypt($shop_id,'ENCODE');
            $url = Qrcode(http_type ()."/api/user/collection?id={$encrypt}");
            if(!$url){
                return json(['code'=>100,'msg'=>'收款码生成失败']);
            }
            $suffix = pathinfo($url, PATHINFO_EXTENSION);
            $key = md5(time().uuid()).'.'.$suffix;
            $up = new \aliyun\OssDemo();
            $data = $up->uploadFile(ROOT_PATH . 'public' . $url,$key);
            if(!$data){
                return ['code'=>100,'msg'=>'收款码生成失败'];
            }
            $place = "https://jintianjifen.oss-cn-shanghai.aliyuncs.com/".$data;
            if(file_exists (ROOT_PATH . 'public' . $url)){
                unlink (ROOT_PATH . 'public' . $url);
            }
            return ['code'=>200,'msg'=>$place];
        }
    }

    public function collectionRecord(){
        extract (input());
        $record  = Db::name('record r')
            ->join('u_user u','r.record_user_id = u.user_id')
            ->where(['record_shop_id'=>$shop_id,'record_status'=>2,'record_type'=>['in', [1,2]] ])
            ->field(['record_id','user_username','record_shop_balance','record_pay_time','record_remark','record_type','record_jifen','record_money'])
            ->page($page,$limit)
            ->order('record_pay_time DESC')
            ->select();
        return json(['status'=>200,'msg'=>$record]);
    }


    public function addRecordRule(){
        extract (input());
        return json(['status'=>100,'msg'=>'请联系运营商按比例送积分']);
        $count = Db::name("record_rule")->where(['rule_shop_id'=>$shop_id])->count();
        if(5 <= $count){
            return json(['status'=>100,'msg'=>'规则数量已达上限']);
        }
        $is_have = Db::name('record_rule')->where(['rule_shop_id'=>$shop_id,'rule_cash'=>$rule_cash])->count ();
        if(0 < $is_have){
            return json(['status'=>100,'msg'=>'买单金额已存在规则中']);
        }
        $give_jifen_rate = DB::name('jifen_conf')->where(['conf_id'=>27])->value('conf_rate');
        $rate = Db::name('jifen_conf')->where(['conf_id'=>1])->value('conf_rate');
        $give_jifen = $rule_cash * $give_jifen_rate/$rate;
        $give_jifen_rate_num = $give_jifen_rate*100;
        if ($give_jifen > $rule_jifen) {
            return json(['status'=>100,'msg'=>'请赠送收款金额'.$give_jifen_rate_num.'%以上的积分']);
        }
        $param = [
            'rule_shop_id'=>$shop_id,
            'rule_cash'=>$rule_cash,
            'rule_jifen'=>$rule_jifen,
            'rule_add_time'=>date("Y-m-d H:i:s")
        ];
        $res = Db::name('record_rule')->insert ($param);
        if($res){
            return json(['status'=>200,'msg'=>'添加成功']);
        }else{
            return json(['status'=>100,'msg'=>'添加失败']);
        }
    }


    public function deleteRecordRule(){
        extract (input());
        $res = Db::name('record_rule')->where(['rule_id'=>$rule_id])->delete ();
        if($res){
            return json(['status'=>200,'msg'=>'删除成功']);
        }else{
            return json(['status'=>100,'msg'=>'删除失败']);
        }
    }


    public function getRecordRule(){
        extract (input());
        $rule = Db::name("record_rule")
            ->where(['rule_shop_id'=>$shop_id])
            ->order('rule_cash ASC')
            ->select();
			$conf_rate = Db::name('jifen_conf')->where('conf_id',1)->value ('conf_rate');
            $shop_ratio = DB::name('shop')->where('shop_id',$shop_id)->value('shop_ratio');
            if (!empty($shop_ratio) && !empty($rule)) {
				foreach($rule as $k => $v){
					$ratio = (10-$shop_ratio)/10;
					$rule[$k]['rule_jifen'] = floor(($v['rule_cash']*$ratio)/$conf_rate);
				}
            }
        return json(['status'=>200,'msg'=>$rule]);
    }


    public function recordRule(){
        extract (input());
        $shop_id = $this->encrypt($encrypt,'DECODE');
        $rule = Db::name("record_rule")
            ->where(['rule_shop_id'=>$shop_id])
            ->order('rule_cash ASC')
            ->select();
			//-----
			$conf_rate = Db::name('jifen_conf')->where('conf_id',1)->value ('conf_rate');
            $shop_ratio = DB::name('shop')->where('shop_id',$shop_id)->value('shop_ratio');
            if (!empty($shop_ratio) && !empty($rule)) {
				foreach($rule as $k => $v){
					$ratio = (10-$shop_ratio)/10;
					$rule[$k]['rule_jifen'] = floor(($v['rule_cash']*$ratio)/$conf_rate);
				}
            }
			//-----
        $data = Db::name('jifen_conf')
            ->where(['conf_id'=>['in','23,24']])
            ->select ();
        $shop_name = Db::name('shop')->where(['shop_id'=>$shop_id])->value('shop_name');
		if(empty($shop_ratio)){
			$typetypeee = 1;
			$ratio = 0;
		}else{
			$typetypeee = 2;
			$ratio = (10-$shop_ratio)/10;
		}
        return json(['status'=>200,'msg'=>$rule,'data'=>$data,'shop'=>$shop_name,'type'=>$typetypeee,'ratio'=>$ratio,'conf_rate'=>$conf_rate]);
    }

    public function getCompayss()
    {
//        $data = Db::name('admin')->where('groupid',3)->select();
//        foreach ($data as $k => $v){
//            $id = $v['id'];
//            $myarea = $v['area'];
//            $qu = Db::name('admin')->where('id',$id)->value('integral');
//            $midd = Db::name('d_jifen')->where(['co_from'=>$myarea,'co_status'=>1])->sum("co_jifen");
//            $shop = Db::name('shop')->where('shop_qu_id',$myarea)->sum('shop_integral');
//            $user = Db::name('jifen')->where('jifen_from',$myarea)->sum('jifen_number');
//            $alls = $qu+$shop+$user+$midd;
//            if($alls > 5000000){
//                Db::name('admin')->where('id',$id)->setDec('integral',$alls-5000000);
//            }
//            if($alls < 5000000){
//                Db::name('admin')->where('id',$id)->setInc('integral',5000000-$alls);
//            }
//        }
//        die;
        $company_type = [
            1 => '个体户',
            2 => '企业'
        ];
        $company_sale1 = [ //719 720 721  719
            1 => '餐饮(提供《食品经营许可证》或《餐饮服务许可证》)',
            2 => '食品生鲜(提供《食品经营许可证》或《食品生产许可证》)',
            3 => '私立/民营医院/诊所(提供《医疗机构执业许可证》)',
            4 => '保健器械/医疗器械(提供《医疗器械经营企业许可证》)',
            6 => '互联网售药(提供《互联网药品交易服务证》)',
            7 => '线下门店卖药(提供《药品经营许可证》)',
            8 => '游艺厅/KTV(提供《娱乐场所许可证》)',
            9 => '网吧(提供《网络文化经营许可证》)',
            10 => '机票/机票代理(提供《航空公司营业执照》或《航空公司机票代理资格证》)',
            11 => '宠物医院(提供《动物诊疗许可证》)',
            12 => '学科类培训机构(提供办学许可证或相关批文)',
            13 => '驾校培训(提供有“驾驶员培训”项目的《道路运输经营许可证》)',

            14 => '话费通讯(提供与运营商间的合作授权收费协议)',

            15 => '加油(《成品油批发经营批准证书》或《成品油仓储经营批准证书》或《成品油零售经营批准证书》)',

            101 => '零售批发/生活娱乐/其他',
        ];
        $company_sale2 = [ //716 728 717 716
            31 => '餐饮(提供《食品经营许可证》或《餐饮服务许可证》)',
            32 => '食品生鲜(提供《食品经营许可证》或《食品生产许可证》)',
            33 => '电信运营商/宽带收费(提供《电信业务经营许可证》)',
            34 => '私立/民营医院/诊所(提供《医疗机构执业许可证》)',
            35 => '保健器械/医疗器械(提供《医疗器械经营企业许可证》)',
            37 => '互联网售药(提供《互联网药品交易服务证》)',
            38 => '线下门店卖药(提供《药品经营许可证》)',
            39 => '游艺厅/KTV(提供《娱乐场所许可证》)',
            40 => '网吧(提供《网络文化经营许可证》)',
            41 => '机票/机票代理(提供《航空公司营业执照》或《航空公司机票代理资格证》)',
            42 => '宠物医院(提供《动物诊疗许可证》)',
            43 => '旅行社(提供《旅行社业务经营许可证》)',
            44 => '宗教组织(提供《宗教活动场所登记证》)',
            45 => '房产中介(提供《宗教活动场所登记证》)',
            46 => '共享服务(需提供资金监管协议)',
            47 => '文物经营/文物复制品销售(提供《文物经营许可证》)',
            48 => '拍卖(提供《拍卖经营批准证书》)',
            49 => '典当(提供《典当经营许可证》)',
            50 => '学科类培训机构(提供办学许可证或相关批文)',
            51 => '驾校培训(提供有“驾驶员培训”项目的《道路运输经营许可证》)',

            52 => '话费通讯(提供与运营商间的合作授权收费协议)',

            53 => '加油(《成品油批发经营批准证书》或《成品油仓储经营批准证书》或《成品油零售经营批准证书》)',

            201 => '零售批发/生活娱乐/其他',
        ];
        return json(['status' => 200,'msg' => $company_type,'company_sale1' => $company_sale1,'company_sale2' => $company_sale2]);
    }
    //----------------------------------------------------------------------------------------------------------------------------------------
    /**
     * 积分充值提示
     */
    public function jifenCz()
    {
        return json(['status' => 100,'msg' => '请前往用户端我的小店使用此功能~']);
    }
    /**
     * 密码修改
     */
    public function editPass()
    {
        $pass = input('password');
        $shop_id = input('shop_id');
        Db::name('shop')
            ->where('shop_id',$shop_id)
            ->update([
                'shop_password' => md5($pass)
            ]);
        return json(['status' => 200,'msg' => '密码修改成功~']);
    }
    /**
     * 获取我的商户列表和子商户列表以及各个判断条件
     */
    public function getMyShops()
    {
        extract (input());
        $data = [];
        $showAdd = 0;
        if($shop_id){
            $mydata = $this->getShopInfoForBase($shop_id);
            $data = Db::name('shop')
                ->where('shop_id',$shop_id)
                ->whereOr('shop_mww_fid',$shop_id)
                ->order('shop_id asc')
                ->field('shop_id,shop_name,shop_account,shop_time,shop_mww_main')
                ->select ();
            if($mydata['shop_mww_main'] == 1) $showAdd = 1;
        }
        return json(['status' => 200,'msg' => $data,'showAdd' => $showAdd]);
    }
    /**
     * 新增子商户
     */
    public function addMySonShop()
    {
        extract (input());
        $userYet = Db::name('u_user')->where('user_phone', $user_phone)->find();
        if(!$userYet) return json(['status' => 100,'msg' => '无此手机端用户']);
        $shopYet = Db::name('shop')
            ->where('shop_account', $user_phone)
            ->whereOr('shop_son', $user_phone)
            ->find();
        if($shopYet) return json(['status' => 100,'msg' => '此手机号已经申请或者成为商户了！']);
        $mydata = $this->getShopInfoForBase($shop_id,2);
        if($mydata['shop_mww_main'] == 2) return json(['status' => 100,'msg' => '您无权添加子商户']);
        if($mydata['dx_status'] != 2 || $mydata['dx_qian_status'] != 2 || !$mydata['dx_mch_id']) return json(['status' => 100,'msg' => '您还没有签约翼支付']);
        //以防万一，校准下
        $mchid = Db::name('shop_copy')->where('sc_shop_id',$shop_id)->value('sc_dx_mch_id');
        if(!$mchid) return json(['status' => 100,'msg' => '商户数据翼支付状态有误，请联系客服']);
        $today = date('Y-m-d H:i:s');
        $shop = [
            'shop_user_id'        => $userYet['user_id'],
            'shop_account'        => $user_phone,
            'shop_password'       => md5($password),
            'shop_name'           => $name,
            'shop_ratio'           => $shop_ratio,
            'shop_range'          => '',
            'shop_remark'         => '',
            'shop_contact'        => $user_phone,
            'shop_address'        => '',
            'shop_hand_img'       => '',
            'shop_facade_img'     => '',
            'shop_ldentity_img'   => '',
            'shop_sheng_id'       => $mydata['shop_sheng_id'],
            'shop_city_id'        => $mydata['shop_city_id'],
            'shop_time'           => $today,
            'shop_authentication_time' => $today,
            'shop_qu_id'          => $mydata['shop_qu_id'],
            'shop_lon'            => '',
            'shop_lat'            => '',
            'shop_superior_agent' => $mydata['shop_superior_agent'],
            'shop_attestation'    => 2,
            'shop_rand'           => $password,
            'dx_status'           => 2,
            'dx_qian_status'           => 2,
            'dx_mch_id'           => $mydata['dx_mch_id'],
            'shop_mww_main'           => 2,
            'shop_mww_fid'           => $shop_id,
        ];
        Db::startTrans();
        try {
            $id = Db::name('shop')->insertGetId($shop);
            Db::name('u_user')->where('user_phone', $user_phone)->update([
                'user_shop_id' => $id,
                'user_level2' => 2,
                'user_one_pay' => 3,
                'user_edit_time' => $today
            ]);
            $insert = [
                'sc_shop_id' => $id,
                'sc_status' => 3,
                'sc_time' => date('Y-m-d H:i:s'),
                'sc_dx_mch_status' => 2,
                'sc_dx_mch_id' => $mydata['dx_mch_id'],
            ];
            Db::name('shop_copy')->insert($insert);
            Db::commit();
            return json(['status' => 200, 'msg' => '添加成功']);
        } catch (\Exception $e) {
            Db::rollback();
            return json(['status' => 100, 'msg' => '添加失败']);
        }
    }
    /**
     * 删除子商户
     */
    public function delMyShop()
    {
        extract (input());
        if($sid == $shop_id) return json(['status' => 100, 'msg' => '不能删除自己']);
        Db::startTrans();
        try {
            $uid = Db::name('shop')->where('shop_id',$sid)->value('shop_user_id');
            Db::name('u_user')->where('user_id', $uid)->update([
                'user_one_pay' => 1,
                'user_level2' => 1,
                'user_shop_id' => '',
            ]);
            Db::name('shop')->where('shop_id',$sid)->delete ();
            Db::name('shop_copy')->where('sc_shop_id',$sid)->delete ();
            Db::commit();
            return json(['status' => 200, 'msg' => '删除成功']);
        } catch (\Exception $e) {
            Db::rollback();
            return json(['status' => 100, 'msg' => '删除失败']);
        }
    }
    public function getWhere($where,$sid,$shop_id){
        if($sid == -1){
            $sids = Db::name('shop')
                ->where('shop_id',$shop_id)
                ->whereOr('shop_mww_fid',$shop_id)
                ->column('shop_id');
            $where['record_shop_id'] = ['in',$sids];
        }
        return $where;
    }
    /**
     * 获取谋商户数据信息：今日数据和昨日数据
     * type：1今日  2昨日
     */
    public function getMyShopData()
    {
        extract (input());
        $rate = Db::name('jifen_conf')->where('conf_id',1)->value ('conf_rate');
        $where = [
            'record_shop_id' => $sid,
            'record_status' => 2
        ];
        $where = $this->getWhere($where,$sid,$shop_id);
        $timeType = 'd';
        if($type == 2) $timeType = 'yesterday';
        $data = Db::name('record')
            ->where($where)
//            ->whereTime('record_add_time',$timeType)
            ->order('record_pay_time desc')
            ->field('record_money,RIGHT(record_pay_time,5) paytime')
            ->page(1,5)
            ->select ();
        $todayCashNum = Db::name('record')
            ->where($where)
            ->where('record_type','<>',2)
            ->whereTime('record_add_time',$timeType)
            ->order('record_pay_time desc')
            ->field('record_money,RIGHT(record_pay_time,5) paytime')
            ->count ();
        $todayCashMoney = Db::name('record')
            ->where($where)
            ->where('record_type','<>',2)
            ->whereTime('record_add_time',$timeType)
            ->sum ('record_money');
        $todayJifenNum = Db::name('record')
            ->where($where)
            ->where('record_type',2)
            ->whereTime('record_add_time',$timeType)
            ->order('record_pay_time desc')
            ->field('record_money,RIGHT(record_pay_time,5) paytime')
            ->count ();
        $todayJifenMoney = Db::name('record')
            ->where($where)
            ->where('record_type',2)
            ->whereTime('record_add_time',$timeType)
            ->sum ('record_money');
        $info = [
            'CashNum' => $todayCashNum,
            'CashMoney' => $todayCashMoney,
            'JifenNum' => $todayJifenNum,
            'JifenMoney' => $todayJifenMoney,
        ];
        //---图形--
        $tu_date = $this->getNumsDays(5);
        $res = array();
        foreach ($tu_date['data'] as $key=>$vo){
            $aa = Db::name('record')
                ->where($where)
                ->where('record_pay_time','between',$vo)
                ->sum ('record_money');
            $res[] = $aa;
        }
        $echarts = [
            'date' => $tu_date['dates'],
            'value' => $res,
        ];
        $one = Db::name('record')
            ->where($where)
            ->where('record_type','<>',2)
            ->whereTime('record_add_time',$timeType)
            ->sum ('record_give_jifen');
        if($one > 0){
            $info['CashMoney'] = $todayCashMoney - ($one * $rate);
            $one = '(送出'.$one.'积分)';
        }else{
            $one = '';
        }
        return json([
            'status' => 200,'msg' => $data,'info' => $info,'echarts' => $echarts,
            'one' => $one,
            'imageUrl' => 'https://jintianjifen.oss-cn-shanghai.aliyuncs.com/c3411bbe38a3adf6dde86af81467fb04.jpg']);
    }
    /**
     * 获取谋商户数据详情账单数据
     *
     */
    public function getMyShopDataInfo()
    {
        extract (input());
//        $sid  = 834;$page=1;
        $where = [
            'record_shop_id' => $sid,
            'record_status' => 2
        ];
        $where = $this->getWhere($where,$sid,$shop_id);
        $data = Db::name('record')
            ->where($where)
            ->field('sum(record_money) allmoney,LEFT(record_pay_time,10) paytime,count(record_id) allnums')
            ->order('paytime desc')
            ->group('paytime')
            ->page($page,15)
            ->select ();
        if($data){
            $rate = Db::name('jifen_conf')->where('conf_id',1)->value ('conf_rate');
            foreach ($data as $k => $v){
                $son = Db::name('record r')
                    ->join('u_user u','r.record_user_id = u.user_id')
                    ->join('up_shop s','r.record_shop_id = s.shop_id')
                    ->where($where)
                    ->where('record_add_time','between',[$v['paytime'] . ' 00:00:00',$v['paytime'] . ' 23:59:59'])
                    ->order('record_pay_time desc')
                    ->field(['record_id','user_username','shop_name','record_shop_balance','record_pay_time','record_remark','record_type','record_jifen','record_give_jifen','record_money'])
                    ->select ();
                if($son){
                    $sendJf = 0;
                    foreach ($son as $k2 => $v2){
                        $son[$k2]['one'] = '';
                        $son[$k2]['two'] = '';
                        if($v2['record_type'] == 1){
                            if($v2['record_give_jifen'] > 0) {
                                $son[$k2]['one'] = '(赠送' . $v2['record_give_jifen'] . '积分)';
                                $son[$k2]['record_money'] = $v2['record_money'] - ($v2['record_give_jifen'] * $rate);
                                $data[$k]['allmoney'] = $data[$k]['allmoney'] - ($v2['record_give_jifen'] * $rate);
                                $sendJf += $v2['record_give_jifen'];
                            }
                            $son[$k2]['two'] = '(翼支付)';
                        }elseif ($v2['record_type'] == 2){
                            $son[$k2]['one'] = '(' . $v2['record_jifen'] . '积分)';
                        }else{
                            if($v2['record_give_jifen'] > 0) {
                                $son[$k2]['one'] = '(赠送' . $v2['record_give_jifen'] . '积分)';
                                $son[$k2]['record_money'] = $v2['record_money'] - ($v2['record_give_jifen'] * $rate);
                                $data[$k]['allmoney'] = $data[$k]['allmoney'] - ($v2['record_give_jifen'] * $rate);
                                $sendJf += $v2['record_give_jifen'];
                            }
                            $son[$k2]['two'] = '(刷脸支付)';
                        }
                        if($sid == -1) $son[$k2]['record_pay_time'] = '('.$v2['shop_name'].')'.$v2['record_pay_time'];
                    }
                    if($sendJf > 0) $data[$k]['allmoney'] = $data[$k]['allmoney'] . '(送出'.$sendJf.'积分)';
                }
                $data[$k]['son'] = $son;
            }
        }
        return json(['status' => 200,'msg' => $data]);
    }

    /**
     * 获取谋商户本周或本月图形数据
     * type：1本周数据  2本月数据
     */
    public function getShopEchartData()
    {
        extract (input());
//        $sid  = 834;$page=1;
        $where = [
            'record_shop_id' => $sid,
            'record_status' => 2
        ];
        $where = $this->getWhere($where,$sid,$shop_id);
        $tu_date = $this->getNumsDays($type);
        $res = array();
        foreach ($tu_date['data'] as $key=>$vo){
            $aa = Db::name('record')
                ->where($where)
                ->where('record_pay_time','between',$vo)
                ->sum ('record_money');
            $res[] = $aa;
        }
        $echarts = [
            'date' => $tu_date['dates'],
            'value' => $res,
        ];
        return json(['status' => 200,'msg' => $echarts]);
    }
    /**
     * 流水明细下载
     * type：1本周数据  2本月数据
     */
    public function waterDownload()
    {
        extract (input());
        $return = [
            'status' => 0,
            'msg' => '此时间段没有数据',
            'msg2' => '此时间段没有数据',
        ];
//        $sid = 1;
//        $start = '2021-09-09';
//        $end = '2021-10-09';
        $where = [
            'record_shop_id' => $sid,
            'record_status' => 2
        ];
        $son = Db::name('record r')
            ->join('u_user u','r.record_user_id = u.user_id')
            ->where($where)
            ->where('record_add_time','between',[$start . ' 00:00:00',$end . ' 23:59:59'])
            ->order('record_pay_time desc')
            ->field(['record_number','user_username','record_money','record_money one','record_shop_balance','record_pay_time','record_remark','record_type','record_jifen','record_give_jifen'])
            ->select ();
        if($son){
            $rate = Db::name('jifen_conf')->where('conf_id',1)->value ('conf_rate');
            foreach ($son as $k2 => $v2){
                $son[$k2]['one'] = '';
                if($v2['record_type'] == 1){
                    if($v2['record_give_jifen'] > 0) {
                        $son[$k2]['one'] = '(赠送' . $v2['record_give_jifen'] . '积分)';
                        $son[$k2]['record_money'] = $v2['record_money'] - ($v2['record_give_jifen'] * $rate);
                    }
                    $son[$k2]['one'] .= '(翼支付)';
                }elseif ($v2['record_type'] == 2){
                    $son[$k2]['one'] = '(' . $v2['record_jifen'] . '积分)';
                }else{
                    if($v2['record_give_jifen'] > 0) {
                        $son[$k2]['one'] = '(赠送' . $v2['record_give_jifen'] . '积分)';
                        $son[$k2]['record_money'] = $v2['record_money'] - ($v2['record_give_jifen'] * $rate);
                    }
                    $son[$k2]['one'] .= '(刷脸支付)';
                }
                unset($son[$k2]['record_type']);
                unset($son[$k2]['record_jifen']);
                unset($son[$k2]['record_give_jifen']);
            }
            $cellname = ['流水号','支付用户','收入金额','说明','余额','支付时间','备注'];
            $res = $this->exportExcelexportExcel('dataInfo',time() . $sid,$cellname,$son);
            $url =  http_type ();
            $return = [
                'status' => 200,
                'msg' => '点击确定复制链接，输入浏览器打开或下载，链接只保留30天('.$url . $res['msg'].')',
                'msg2' => $url . $res['msg']
            ];
        }
        return json($return);
    }
    public function delExcel()
    {
        //-------------------------------------------------
        $dateTen = date("Y-m-d H:i:s",(time() - 3600 * 24 * 10));
        $data = Db::table('up_order')
            ->where('o_add_time','<=',$dateTen)
            ->where('o_type',1)
            ->where('o_status',2)
            ->where('o_pay_status',2)
            ->where('o_pay_type',3)
            ->where('o_ttt',1)
            ->where('o_jifen','>',0)
            ->page(1,10)
            ->field('o_id,o_jifen,o_user_id,o_add_time')
            ->select();
        if($data){
                foreach ($data as $k => $v){
                    $user_id = $v['o_user_id'];
                    $have = Db::name('jifen')->where(['jifen_user_id'=>$user_id])->find();
                    if($have){
                        Db::startTrans();
                        try {
                            $sum = Db::name('jifen')->where(['jifen_user_id'=>$user_id])->sum('jifen_number');
                            $res = Db::name('jifen')->where('jifen_id', $have['jifen_id'])->setInc("jifen_number",$v['o_jifen']);
                            $res = Db::name('u_user')->where('user_id',$user_id)->setField('user_integral',$sum+$v['o_jifen']);
                            $res = Db::name('order')->where('o_id', $v['o_id'])->update([
                                'o_status' => 12,
                                'o_ttt' => 2
                            ]);
                            Db::commit();
                        } catch (\Exception $e) {
                            Db::rollback();
                        }

                    }
                }

        }
        $date = date("Ymd",(time() - 3600 * 24 * 31));
        $dirname = ROOT_PATH . 'public' . DS . 'excel/' . $date;
        $result = false;
        if (!is_dir($dirname)) {
            exit('no');
        }
        $handle = opendir($dirname); //打开目录
        while (($file = readdir($handle)) !== false) {
            if ($file != '.' && $file != '..') {
                //排除"."和"."
                $dir = $dirname .'/' . $file;
                unlink($dir);
            }
        }
        closedir($handle);
        $result = rmdir($dirname) ? true : false;

        exit('success');
    }
    public function getShopInfoForBase($shop_id,$type=1){
        if($type == 2){
            $data = Db::name('shop')
                ->where('shop_id',$shop_id)
                ->find();
        }else{
            $data = Db::name('shop')
                ->where('shop_id',$shop_id)
                ->field('shop_id,shop_name,shop_account,shop_time,shop_mww_main,shop_user_id')
                ->find();
        }
        return $data;
    }
    public function getNumsDays($nums){
        //1代表本周日期，2代表本月日期，其他则对应天数
        if($nums == 1) $nums = date('N');
        if($nums == 2) $nums = date('d');
        $today = date('Y-m-d');
        $time = strtotime($today);
        $data = [];
        $dates = [];
        for($i=$nums-1;$i>=0;$i--){
            $value = date("Y-m-d", ($time - 3600*24*$i));
            $dates[] = substr($value,5,5);
            $data[] = [$value . ' 00:00:00',$value . ' 23:59:59'];
        }
        return ['dates' => $dates , 'data' => $data];
    }
    public function exportExcelexportExcel($file_name1,$file_name2,$title,$list,$status='',$values='')
    {
        set_time_limit(0);//防止超时
        //ini_set("memory_limit", "512M");//防止内存溢出
        $date = date('Ymd');
        $dir = ROOT_PATH . 'public' . DS . 'excel/' . $date;
        if(!file_exists($dir)){
            //检查是否有该文件夹，如果没有就创建，并给予最高权限
            mkdir($dir, 0700,true);
        }
        $file_name = $file_name1 . $file_name2 . '.csv';
        $path = ("{$dir}/".iconv('UTF-8','gb2312',$file_name));
        $file = fopen($path, 'w');
        $limit = 100000;
        $calc = 0;
        foreach ($title as $v){
            $tit[] = iconv('UTF-8', 'GB2312//IGNORE',$v);
        }
        fputcsv($file,$tit);
        foreach ($list as $v){
            $calc++;
            if($limit == $calc){
                ob_flush();
                flush();
                $calc = 0;
            }
            foreach($v as $kk => $t){
                if($status){
                    if(in_array($kk,$status) && isset($values[$kk][$t]) && $values[$kk][$t]){
                        $t = $values[$kk][$t];
                    }
                }
                $t = $t . "\t";
                $tarr[] = iconv('UTF-8', 'GB2312//IGNORE',$t);
            }
            fputcsv($file,$tarr);
            unset($tarr);
        }
        unset($list);
        fclose($file);
        $filePath = 'excel/' . $date . '/' . $file_name;
        $result = array( 'code' => 200, 'msg' =>"/".$filePath );
        return $result;
    }
}